Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert multiple instances of a character to only one (aa = a) using preg_replace?

I have a string, I want to convert multiple appearances of - to just one -.

I have tried preg_replace('/--+/g', '-', $string) but that simply returns nothing..

like image 492
Hailwood Avatar asked Sep 07 '12 11:09

Hailwood


People also ask

What is use of Preg_replace in PHP?

The preg_replace() function returns a string or array of strings where all matches of a pattern or list of patterns found in the input are replaced with substrings.

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.

What is Regex in PHP?

A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for. A regular expression can be a single character, or a more complicated pattern.

What is quantifiers in PHP?

Quantifiers specify how many instances of a character, group, or character class must be present in the input for a match to be found. The following table lists the quantifiers supported by .NET: Greedy quantifier. Lazy quantifier.


1 Answers

You should not use g in the pattern, and you can simplify your regular expression:

preg_replace('/-+/', '-', $string);

Backslash escapes are not required.

On http://ideone.com/IOlpv:

<?
$string = "asdfsdfd----sdfsdfs-sdf-sdf";
echo preg_replace('/-+/', '-', $string);
?>

Output:

asdfsdfd-sdfsdfs-sdf-sdf
like image 164
ronalchn Avatar answered Sep 30 '22 14:09

ronalchn