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 thes开发者_StackOverflow社区e 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);
You can't do that with just str_replace
. Either use a combination of explode
, strip
and implode
, or user preg_replace
.
Edit: preg_replace('/\s*<!>\s*', PHP_EOL, $string);
should be better.
Sure, str_replace('<!>', "\n", $string);
if your example is complete.
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);
精彩评论