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
I think str_replace()
might be more appropriate here:
$id = "aa aa";
$id = str_replace(' ', '_', $id);
echo $id;
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;
?>
You have forgotten to assign the result of preg_replace
into your $id
$id = preg_replace('/\s+/', '_', $id);
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);
Sometimes, in linux/unix environment,
$strippedId = preg_replace('/\h/u', '', $id);
Try this as well.