简体   繁体   English

PHP str_replace用下划线替换空格

[英]PHP str_replace replace spaces with underscores

Is there a reason that I'm not seeing, why this doesn't work? 有没有理由我没有看到,为什么这不起作用?

    $string = $someLongUserGeneratedString;
    $replaced = str_replace(' ', '_', $string);
    echo $replaced;

The output still includes spaces... Any ideas would be awesome 输出仍然包含空格......任何想法都会很棒

I'll suggest that you use this as it will check for both single and multiple occurrence of white space (as suggested by Lucas Green). 我建议您使用它,因为它将检查单个和多个出现的空白区域(如Lucas Green所建议的)。

$journalName = preg_replace('/\s+/', '_', $journalName);

instead of: 代替:

$journalName = str_replace(' ', '_', $journalName);

Try this instead: 试试这个:

$journalName = preg_replace('/\s+/', '_', $journalName);

Explanation: you are most likely seeing whitespace, not just plain spaces (there is a difference). 说明:您最有可能看到空格,而不仅仅是普通空格(存在差异)。

For one matched character replace, use str_replace : 对于一个匹配的字符替换,请使用str_replace

$string = str_replace(' ', '_', $string);

For all matched character replace, use preg_replace : 对于所有匹配的字符替换,请使用preg_replace

$string = preg_replace('/\s+/', '_', $string);

Try this instead: 试试这个:

$journalName = str_replace(' ', '_', $journalName);

to remove white space 删除空白区域

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

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