user3436399
user3436399

Reputation: 77

preg_replace vs trim PHP

I am working with a slug function and I dont fully understand some of it and was looking for some help on explaining.

My first question is about this line in my slug function $string = preg_replace('# +#', '-', $string); Now I understand that this replaces all spaces with a '-'. What I don't understand is what the + sign is in there for which comes after the white space in between the #.

Which leads to my next problem. I want a trim function that will get rid of spaces but only the spaces after they enter the value. For example someone accidentally entered "Arizona " with two spaces after the a and it destroyed the pages linked to Arizona.

So after all my rambling I basically want to figure out how I can use a trim to get rid of accidental spaces but still have the preg_replace insert '-' in between words.

ex.. "Sun City West " = "sun-city-west"

This is my full slug function-

function getSlug($string){
if(isset($string) && $string <> ""){
    $string = strtolower($string);
    //var_dump($string); echo "<br>";
    $string = preg_replace('#[^\w ]+#', '', $string);
    //var_dump($string); echo "<br>";
    $string = preg_replace('# +#', '-', $string);
}
return $string;

}

Upvotes: 2

Views: 3743

Answers (2)

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

You can try this:

function getSlug($string) {
  return preg_replace('#\s+#', '-', trim($string));
}

It first trims extra spaces at the beginning and end of the string, and then replaces all the other with the - character.

Here your regex is:

#\s+#

which is:

#  = regex delimiter
\s = any space character
+  = match the previous character or group one or more times
#  = regex delimiter again

so the regex here means: "match any sequence of one or more whitespace character"

Upvotes: 5

Majenko
Majenko

Reputation: 1840

The + means at least one of the preceding character, so it matches one or more spaces. The # signs are one of the ways of marking the start and end of a regular expression's pattern block.

For a trim function, PHP handily provides trim() which removes all leading and trailing whitespace.

Upvotes: 2

Related Questions