Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace all spaces

Tags:

php

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 
like image 976
user740521 Avatar asked Nov 17 '11 23:11

user740521


People also ask

How do you replace all spaces in a string?

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.

How do you replace all spaces in a string in TypeScript?

Use the replace() method to remove all whitespace from a string in TypeScript, e.g. str. replace(/\s/g, '') .

What is the difference between Str_replace and Preg_replace?

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.


2 Answers

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); 
like image 192
Mark Byers Avatar answered Sep 30 '22 20:09

Mark Byers


I think str_replace() might be more appropriate here:

$id = "aa aa"; $id = str_replace(' ', '_', $id); echo $id; 
like image 42
Clive Avatar answered Sep 30 '22 21:09

Clive