简体   繁体   English

PHP中的str_replace

[英]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" 并将其替换为“ \\ n”

Can that be achieved with str_replace in php? 可以在PHP中使用str_replace来实现吗?

If you only have those 4 possibilities, yes, then you can do that with str_replace . 如果只有这4种可能性,那么可以使用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 . 当然,您可以通过对str_replace 4次调用来实现。 Edit: I was wrong. 编辑:我错了。 You can use arrays in str_replace . 您可以在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. 还可以考虑使用strtr ,它允许一步完成。

$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: 您当然可以使用str_replace做到这一点:

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

Edit: preg_replace('/\\s*<!>\\s*', PHP_EOL, $string); 编辑: preg_replace('/\\s*<!>\\s*', PHP_EOL, $string); should be better. 应该更好。

Sure, str_replace('<!>', "\\n", $string); 当然, str_replace('<!>', "\\n", $string); if your example is complete. 如果您的示例已完成。

You can't do that with just str_replace . str_replace不能做到这一点。 Either use a combination of explode , strip and implode , or user preg_replace . 可以结合使用explodestripimplode ,也可以使用用户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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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