Regular expressions in PHP - a problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
siminder82
Forum Newbie
Posts: 6
Joined: Thu Jul 10, 2008 8:48 pm

Regular expressions in PHP - a problem

Post 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?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Regular expressions in PHP - a problem

Post by Benjamin »

preg_replace_all() should do the trick with the correct regex.
siminder82
Forum Newbie
Posts: 6
Joined: Thu Jul 10, 2008 8:48 pm

Re: Regular expressions in PHP - a problem

Post 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?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Regular expressions in PHP - a problem

Post by Benjamin »

My bad, I was thinking of preg_match_all(). Why won't preg_replace() work for you?
siminder82
Forum Newbie
Posts: 6
Joined: Thu Jul 10, 2008 8:48 pm

Re: Regular expressions in PHP - a problem

Post 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?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Regular expressions in PHP - a problem

Post 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.
Post Reply