preg_replace all spaces

后端 未结 5 411
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-03 20:28

I\'m trying to replace all spaces with underscores and the following is not working:

$id = \"aa aa\";
echo $id;
preg_replace(\'/\\s+/\', \'_\', $id);
echo $i         


        
相关标签:
5条回答
  • I think str_replace() might be more appropriate here:

    $id = "aa aa";
    $id = str_replace(' ', '_', $id);
    echo $id;
    
    0 讨论(0)
  • 2021-01-03 20:43

    We need to replace the space in the string "aa aa" with '_' (underscore). The \s+ is used to match multiple spaces. The output will be "aa_aa"

    <?php
    
    $id = "aa aa";
    $new_id = preg_replace('/\s+/', '_', $id);
    echo $new_id;
    
    ?>
    
    0 讨论(0)
  • 2021-01-03 20:46

    You have forgotten to assign the result of preg_replace into your $id

    $id = preg_replace('/\s+/', '_', $id);
    
    0 讨论(0)
  • 2021-01-03 20:47

    The function preg_replace doesn't modify the string in-place. It returns a new string with the result of the replacement. You should assign the result of the call back to the $id variable:

    $id = preg_replace('/\s+/', '_', $id);
    
    0 讨论(0)
  • 2021-01-03 20:48

    Sometimes, in linux/unix environment,

    $strippedId = preg_replace('/\h/u', '',  $id);
    

    Try this as well.

    0 讨论(0)
提交回复
热议问题