Reputation: 5113
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
Reputation: 7870
You can perform that in 2 steps:
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
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