PHP str_replace replace spaces with underscores

烂漫一生 提交于 2019-11-28 20:50:02

问题


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


回答1:


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).

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

instead of:

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



回答2:


Try this instead:

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

Explanation: you are most likely seeing whitespace, not just plain spaces (there is a difference).




回答3:


For one matched character replace, use str_replace:

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

For all matched character replace, use preg_replace:

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



回答4:


Try this instead:

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

to remove white space



来源:https://stackoverflow.com/questions/12704613/php-str-replace-replace-spaces-with-underscores

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!