views:

214

answers:

7
+1  Q: 

str_replace in php

hi, 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?

A: 

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

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

chelmertz
+3  A: 

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);
codeholic
@codeholic: You don't need 4 calls to str_replace. And he wanted to replace for "\n"
Vinko Vrsalovic
Yep. You're right.
codeholic
+1  A: 

You certainly can do it with str_replace like this:

$needles = array(" <!> ","<!> "," <!>","<!>");
$result = str_replace($needles,"\n",$text);
Vinko Vrsalovic
Yeah, but what if there is two spaces ? Or a tab ? Do you add a spacial case for each ?
e-satis
@e-satis: The requirements are clear. If the OP didn't mean what he asked about or missed some details, he should edit the question.
Vinko Vrsalovic
A: 

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

e-satis
+5  A: 

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 );
poke
this is it! thanks!
andufo
A: 

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)

Lex
A: 

This is kind of neat:

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