Page 1 of 1

Regular expressions in PHP - a problem

Posted: Wed Jan 28, 2009 10:36 pm
by siminder82
Hi,

Im new to PHP and regular expressions and Ive been having a lot of trouble with a particular case.

My problem is that I need to search for a regular expression in a string and replace a part of the match found. To be specific, I need to replace commas in a string, if and only if, they occur within alphabets but I do not want to replace commas between numbers (like 100,000). How can I solve this problem with regular expressions?

Using preg_replace, Im not able to do this. Is there a function which can help me with this? Can anyone guide me please?

Re: Regular expressions in PHP - a problem

Posted: Wed Jan 28, 2009 10:56 pm
by Benjamin
preg_replace_all() should do the trick with the correct regex.

Re: Regular expressions in PHP - a problem

Posted: Wed Jan 28, 2009 11:44 pm
by siminder82
I just checked the PHP manual (http://www.php.net) for 'preg_replace_all'.

It says there is no such function. Are you sure of this function in PHP?

Re: Regular expressions in PHP - a problem

Posted: Thu Jan 29, 2009 12:47 am
by Benjamin
My bad, I was thinking of preg_match_all(). Why won't preg_replace() work for you?

Re: Regular expressions in PHP - a problem

Posted: Thu Jan 29, 2009 3:21 pm
by siminder82
becoz preg_replace replaces the entire searched pattern (regex) with the replacement. I want to replace only a part of the regex.

e.g the regex searches for pattern \[a-z]\,[a-z]\ and finds a match - "tea,coffee". Now I just want to replace the comma in this matched string and keep everything else the same.

Can you tell me how to do it with preg_replace?

Re: Regular expressions in PHP - a problem

Posted: Thu Jan 29, 2009 4:17 pm
by Benjamin
Here, look at this closely. It's copied from the php.net manual entry for preg_replace()

Code: Select all

 
<?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
Note the three sets of () in the regex. These correspond to $1, $2 (not used) and $3.