用下划线替换空格

时间:2022-08-11 00:14:47

Is there a reason that I'm not seeing, why this doesn't work?

有什么原因让我看不到,为什么这不起作用?

    $journalName = $_POST['journalName'];
    $journalName = str_replace(' ', '_', $journalName);
    $_SESSION['journalName'] = $journalName;
    echo $_SESSION['journalName'];

The output still includes spaces... Any ideas would be awesome

输出仍然包含空格…任何想法都会很棒

4 个解决方案

#1


90  

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

#2


10  

Try this instead:

试试这个:

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

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

说明:您最有可能看到的是空白,而不仅仅是普通的空格(有区别)。

#3


3  

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

#4


0  

Try this instead:

试试这个:

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

to remove white space

删除空格

#1


90  

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

#2


10  

Try this instead:

试试这个:

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

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

说明:您最有可能看到的是空白,而不仅仅是普通的空格(有区别)。

#3


3  

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

#4


0  

Try this instead:

试试这个:

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

to remove white space

删除空格