Log in

View Full Version : PHP Function in Regular expression



bluewalrus
06-08-2010, 06:56 PM
Is there a way to call a php function within a regular expression, for example preg_replace?

This is what I currently have but doesn't work...



$case_changed = preg_replace('/<em>(.*) (.*)</em>/', ucwords($1) . $2, $case_changed);

djr33
06-08-2010, 07:05 PM
Since $1 is a special variable, I'm not surprised it doesn't work. I can't think of an easy way to do this (assuming what you have won't work).

You could do it in several steps: use regex to mark and/or split at the places then replace as needed.
I'd probably do this using arrays, similar to explode(), but using regex. I believe there's a "split by regex" function, then you can loop through the array, do the function, and implode it back together again...

techietim
06-08-2010, 07:09 PM
function change_case($arr)
{
return ucwords($arr[1]) . $arr[2];
}

$case_changed = '<em>Hello World</em>';
$case_changed = preg_replace_callback('/<em>(.*) (.*)<\/em>/', 'change_case', $case_changed);

bluewalrus
06-09-2010, 02:20 PM
That's giving me an error



Warning: preg_replace_callback() [function.preg-replace-callback]: Requires argument 2, 'O-', to be a valid callback

I altered it somewhat



function italic_word($arr) {
return ucwords($arr[1]) . $arr[2];
}
$case_changed = preg_replace_callback('/<em>(.*) (.*)<\/em>/', italic_word($case_changed), $case_changed);

techietim
06-09-2010, 07:04 PM
That's giving me an error



I altered it somewhat



function italic_word($arr) {
return ucwords($arr[1]) . $arr[2];
}
$case_changed = preg_replace_callback('/<em>(.*) (.*)<\/em>/', italic_word($case_changed), $case_changed);

It should be:


$case_changed = preg_replace_callback('/<em>(.*) (.*)<\/em>/', 'italic_word', $case_changed)

bluewalrus
06-09-2010, 09:15 PM
Oh, okay thanks.

So the second parameter there is the function name and the third is the variable being passed in?

techietim
06-09-2010, 11:19 PM
So the second parameter there is the function name and the third is the variable being passed in?

php.net/preg_replace_callback (http://php.net/preg_replace_callback)