简体   繁体   English

PHP str_replace()-用空格替代吗?

[英]PHP str_replace() - Replace with space alternative?

I came across a need today to use str_replace() to replace all hyphens in a string with spaces. 我今天遇到了一种需要,使用str_replace()将字符串中的所有连字符替换为空格。 Easy enough: 很简单:

$string = "Some-test-string";
$string = str_replace('-', ' ', $string);

The thing is, using ' ' (string with empty space) in the "replacement" part of str_replace() just feels so dirty. 问题是,在str_replace()的“ replacement”部分中使用' ' (带空格的字符串str_replace()感觉太脏了。 Also seems brittle... Looks ugly too. 看起来也很脆...看起来也很丑。

Is there no better option? 有没有更好的选择? I tried using a regex pattern in the "replacement" section but that didn't work, it came out literal. 我尝试在“替换”部分中使用正则表达式模式,但这没有用,它是按字面意思显示的。

Ideally, something like this would be great if possible: 理想情况下,如果可能的话,这样的事情会很棒:

$string = "Some-test-string";
$string = str_replace('-', '/\s/', $string);

Thanks! 谢谢!

Edited: Replaced all preg_replace() calls with str_replace() per suggestion. 编辑:每个建议用str_replace()替换所有preg_replace()调用。

I see no reason to use regular expressions in this case. 我认为在这种情况下没有理由使用正则表达式。 Why not use a simpler function, eg strtr() ? 为什么不使用更简单的函数,例如strtr()

$string = "Some-test-string";
$string = strtr($string, '-', ' ');

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

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