Jump to content

Re: Stuck with preg_replace


kcp88

Recommended Posts

all by itself it effectively does nothing, since the returned result of the preg_replace isn't being assigned to anything.  At a minimum, you would have to assign it to a variable, or echo it out, or something.  Point is, the original variable $variable (3rd argument in the function) isn't altered. Example:

 

echo "before: " . $variable . "<br/>";
$variable = preg_replace('/([a-zA-Z]).*/', '$1', $variable);
echo "after: " . $variable;

 

The regex itself basically finds the first instance of a letter (case-insenstive) and removes everything after it. 

 

breakdown of the regex /([a-zA-Z]).*/

 

/ Starting pattern delimiter

( Start of captured group 1

[a-zA-Z] Character class to match 1 of any lowercase or uppercase letter

) End of captured group 1

.* Greedy match of 0 or more of any character (other than newline character)

/ Ending pattern delimiter

 

replace all that was match with...

 

$1  whatever was captured in group 1

 

 

Examples (green is what is matched and captured by capture group 1, red is what is matched by the .*):

 

$variable = "abc"

 

before: abc

after: a

 

$variable = "123 Abc blah";

 

before: 123 Abc blah

after: 123 A

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.