Wasim
Wasim

Reputation: 5113

Regex replace special characters with hyphen except first and last

I'm using this regular expression to format song names to url friendly aliases. It replaces 1 or more consecutive instances of special characters and white space with a hyphen.

$alias = preg_replace("/([^a-zA-Z0-9]+)/", "-", trim(strtolower($name)));

This works fine so if the song name was This is *is* a (song) NAME it would create the alias this-is-a-song-name. But if the name has special characters at the beginning or end *This is a song (name) it would create -this-is-a-song-name- creating hyphens at each end.

How can I modify the regex to replace as it is above, but to replace the first and last special character with empty space.

Upvotes: 2

Views: 1985

Answers (2)

pierroz
pierroz

Reputation: 7870

You can perform that in 2 steps:

  • In the first step, you remove special characters at the beginning and at the end of your string
  • In the second step, you reuse your regex as it is now.

The code could look like this:

$alias = preg_replace("/(^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$)/", "", trim(strtolower($name));
$alias = preg_replace("/([^a-zA-Z0-9]+)/", "-", $alias);

(I haven't tested it but you may get the idea)

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

You need to do a double replacement.

$str = '*This is a song (name)';
$s   = preg_replace('~^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$~', '', $str);
echo preg_replace('~[^a-zA-Z0-9]+~', '-', $s);

Upvotes: 4

Related Questions