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?
Regular expressions in PHP - a problem
Moderator: General Moderators
-
siminder82
- Forum Newbie
- Posts: 6
- Joined: Thu Jul 10, 2008 8:48 pm
Re: Regular expressions in PHP - a problem
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
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?
It says there is no such function. Are you sure of this function in PHP?
Re: Regular expressions in PHP - a problem
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
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?
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
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);
?>
Note the three sets of () in the regex. These correspond to $1, $2 (not used) and $3.The above example will output:
April1,2003