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

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.