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..
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.
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.
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.
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.
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
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