PDA

View Full Version : PHP Function To Search And Replace


Nick
2006.01.08, 03:34 AM
I need to write a PHP function that will search through a string, replacing all instances of '!and!' with &. I've tried a few things, and this looks like it should work... but it doesn't. Can anyone help me with this?


function replace_and_signs($some_text)
{
$new_text = $some_text;
$pos = strpos($new_text, '!and!');
while($pos > 0)
{
substr_replace($new_text, '&', $pos, 5);
$pos = strpos($new_text, '!and!');
}
return $new_text;
}

Nick
2006.01.08, 04:19 AM
Well, I must've just forgotten str_replace or something. Here's the new code that does exactly what I want:

function replace_and_signs($some_text)
{
$new_text = str_replace('!and!', '&', $some_text);
return $new_text;
}

sord
2006.01.15, 12:04 AM
Or you can just forget the function (which takes more time because it has to jump in memory after copying the text and then copy new text to return) and just use a single line str_replace where needed

Nick
2006.01.15, 12:49 PM
I was going to do that, but I've added more symbols that all must be replaced so the function makes sense now. I now check for !and!, /' and a few others that slip through the formatting process before this point.