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
Use the String. replaceAll() method to replace all spaces in a string, e.g. str. replaceAll(' ', '-'); . The replaceAll method will return a new string where all occurrences of a space have been replaced by the provided replacement.
Use the replace() method to remove all whitespace from a string in TypeScript, e.g. str. replace(/\s/g, '') .
str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f. {2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.
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);
I think str_replace()
might be more appropriate here:
$id = "aa aa"; $id = str_replace(' ', '_', $id); echo $id;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With