2

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.

2
  • 2
    Have you thought about using a second filter which trims hyphens from the head and tail of the string if they are present? Commented Mar 4, 2015 at 16:16
  • Yes definitely thought about it but I'd like try and see if it's possible to do it in one regex statement Commented Mar 4, 2015 at 16:18

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.