简体   繁体   中英

str_replace in php

i have a long string that can hold all these values at the same time:

hello<!>how are you? <!>I am fine<!> What is up? <!> Nothing!

I need to find all these posibilities:

' <!> '
' <!>'
'<!> '
'<!>'

And replace them with "\\n"

Can that be achieved with str_replace in php?

If you only have those 4 possibilities, yes, then you can do that with str_replace .

$str = str_replace( array( ' <!> ', ' <!>', '<!> ', '<!>' ), "\n", $str );

Yeah, but what if there is two spaces ? Or a tab ? Do you add a spacial case for each ?

You can either add special cases for each of those, or use regular expressions:

$str = preg_replace( '/\s*<!>\s*/', "\n", $str );

Of course, you can achieve this with 4 calls to str_replace . Edit: I was wrong. You can use arrays in str_replace .

$str = str_replace(' <!> ', "\n", $str);
$str = str_replace(' <!>',  "\n", $str);
$str = str_replace('<!> ',  "\n", $str);
$str = str_replace('<!>',   "\n", $str);

Also consider using strtr , that allows to do it in one step.

$str = strtr($str, array(
    ' <!> ' => "\n",
    ' <!>'  => "\n",
    '<!> '  => "\n",
    '<!>'   => "\n"
));

Or you can use a regular expression

$str = preg_replace('/ ?<!> ?/', "\n", $str);

You certainly can do it with str_replace like this:

$needles = array(" <!> ","<!> "," <!>","<!>");
$result = str_replace($needles,"\n",$text);

Edit: preg_replace('/\\s*<!>\\s*', PHP_EOL, $string); should be better.

Sure, str_replace('<!>', "\\n", $string); if your example is complete.

You can't do that with just str_replace . Either use a combination of explode , strip and implode , or user preg_replace .

You could use:

//get lines in array
$lines = explode("<!>", $string);
//remove each lines' whitesapce
for(i=0; $i<sizeof($lines); $i++){
    trim($lines[$i]);
}
//put it into one string
$string = implode("\n", $lines)

It's a bit tedious, but this should work (also removes two spaces, and tabs). (didn't test the code, so there could be errors)

This is kind of neat:

$array = explode('<!>', $inputstring);
foreach($array as &$stringpart) {
  $stringpart = trim($stringpart);
}
$outputstring = implode("\r\n", $array);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM