Reputation: 1204
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 $id;
prints
aa aaaa aa
Upvotes: 27
Views: 92778
Reputation: 3406
If you have a problem removing all spaces it is because /\s+/
does not match the \u00A0 space
To be sure, always add the "u" after the delimiter, for all unicode spaces and to catch the \u00A0 space too
$text = preg_replace('/\s+/u', '', $text);
Upvotes: 0
Reputation: 113
Sometimes, in linux/unix environment,
$strippedId = preg_replace('/\h/u', '', $id);
Try this as well.
Upvotes: 8
Reputation: 81
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;
?>
Upvotes: 2
Reputation: 36965
I think str_replace()
might be more appropriate here:
$id = "aa aa";
$id = str_replace(' ', '_', $id);
echo $id;
Upvotes: 17
Reputation: 839184
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);
Upvotes: 69
Reputation: 10539
You have forgotten to assign the result of preg_replace
into your $id
$id = preg_replace('/\s+/', '_', $id);
Upvotes: 13