Jump to content

preg_replace explanation


justinh

Recommended Posts

I'm looking at this page about preg_replace:

http://php.net/manual/en/function.preg-replace.php

Which gives this example:


<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>

The above example will output:

April1,2003

I don't understand the transformation, how they go the answer.  Can someone explain?

Thanks,

Justin

Link to comment
Share on other sites

This part is replaced by the first matched pattern:

${1}

Then there's a 1 and a comma:

1,

Then the third matched pattern: 

$3

The reason why the curly brackets are there is to show how to reference a numbered pattern when you immediately want another digit to follow in the replacement (in this case, they want a 1 in the replacement).

Link to comment
Share on other sites

Okay, I'll need a much greater breakdown that that... :huh:

First, how to understand the value for $pattern.  Then, where is the second matched pattern?  (it looks like we are missing one)  Then, why are there no spaces in the output string?

It just looks way too complicated to replace only the day, as it looks like it is matching the entire string and carrying forward some of the original string instead of just what needs to be replaced.

Edited by justinh
Link to comment
Share on other sites

If you want to understand the pattern syntax, check here:

http://php.net/manual/en/pcre.pattern.php

The pattern looks for one or more word characters, then a space, then one or more digits, then a comma and a space, then one or more digits.  Each of those sub-patterns is captured because they have parentheses around them.

Then, where is the second matched pattern?

It's not used in the replacement.  This example is just to illustrate how you refer to a sub-pattern when you want to output a number after it.

Then, why are there no spaces in the output string?

Because the replacement pattern has no spaces in it, and the spaces aren't part of what was captured.

Link to comment
Share on other sites

Thank you so much - I understand it now after finally putting all the pieces together.  I also figured out (from the link you provided) that the pattern string has to be enclosed by a delimiter, thus the two "/".  Then the ending "i" mean case-insensitive alpha match.  Just for anyone else that reads this post...

It looks to me like someone could specialize just in regex coding!

Thanks again.

  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...