Forum Moderators: coopster

Message Too Old, No Replies

Ignoring Linebreaks with str_replace

Can you tell php to ignore linebreaks when parsing text?

         

geckofuel

12:25 pm on Jul 16, 2003 (gmt 0)

10+ Year Member



I need to be able to ignore linebreaks in php when parsing text. Does anyone know how to do this? I've searched the php.net manual and come up empty.

redshift

12:47 pm on Jul 16, 2003 (gmt 0)

10+ Year Member



Although I can't figure out your problem maybe this can give you a hint.

Replacing linebreaks can be done with:


$string = preg_replace("(\r\n¦\n¦\r)", $replace_with, $string);

vincevincevince

4:41 pm on Jul 16, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



yes, preg_replace will do all fancy replaces that str_replace can't do

for example, if i want to match both "Hello World" and "Hello \n World" (\n being line break), then i can do:


preg_replace("/Hello [\n]{0,1}World/","change it to this",$input);

as i suspect you want to support a linebreak in any random place, then i would first backup the string...


$temp=$input;

now i want to try and find the string i'm looking to replace ($search), using the check:

preg_match("/$search/",$input);

if this can be found, then we can replace it

preg_replace("/$search/",$change_to,$temp);

now, if it can't be found, maybe it's because there is a linebreak within it, so we want to remove each linebreak in turn:

if(strpos("\n",$temp)) //ie, only if there is one to change
{
$test=preg_replace("/\n/","",$temp,1); //ie, remove the first linebreak to be found in $temp
}

now, we want to see if the string can be found, if so where:

if ($strpos=strpos($test,$test))
{
//now we replace in the "master string" $temp this place
$temp=substr_replace($temp,$change_to,$strpos,strlen($search)+strlen("\n"));
//ie, we find that part of $temp which corresponds to the matched string in $test and replace it
}

our next problem is that we have to remember we've dealt with that \n, and move on to the next. for this i suggest changing \n to \a:

$temp=preg_replace("/\n/","\a",$temp,1);

now putting this all together, we have a lovely search and replace loop, which doesn't worry about linebreaks:


<?php
$input="Mrs Smith's cat\n went splat cat \nwent splat.";
$search="cat went";
$change_to="dog said";

$temp=preg_replace("/$search/",$change_to,$input);
while(preg_match("/\n/",$temp)) //ie, only if there is one to change
{
$test=preg_replace("/\n/","",$temp,1); //ie, remove the first linebreak to be found in $temp
if ($strpos=strpos($test,$search)) //ie, if the search can be found now
{
//now we replace in the "master string" $temp this place
$temp=substr_replace($temp,$change_to,$strpos,strlen($search)+strlen("\n"));
//ie, we find that part of $temp which corresponds to the matched string in $test and replace it
}
$temp=preg_replace("/\n/","\a",$temp,0);
}
$output=str_replace("\a","\n",$temp);

echo $output;
?>