1

how would I extend this preg_replace (in PHP), using regular expressions to replace white spaces also..

$this->permalink = preg_replace('[^a-z0-9]', '-', $this->permalink);

It's for generating page permalinks based on a page title. 'About me' will become 'about-me'. everything's fine except it doesn't remove the space yet.

Thanks!

3
  • Honestly, you should probably try a quick regex tutorial. This is really basic stuff. Commented Jul 10, 2011 at 17:34
  • You could change your regex to [^a-z0-9]|\s, but your above expression works for me. Commented Jul 10, 2011 at 17:34
  • That didn't work. '|' broke the function. Commented Jul 10, 2011 at 17:39

2 Answers 2

2

As pointed out in the comment, you're regular expression is missing the delimiters. I've also added the i modifier so that it's case-insensitive.

Example:

$this->permalink = preg_replace('/[^a-z0-9]/i', '-', $this->permalink);

Here's a working example: http://codepad.org/OlzQax1c.

Sign up to request clarification or add additional context in comments.

4 Comments

This is still wrong. His regex will remove spaces, but he's missing the / delimiters.
@coreyward - You're absolutely correct. I've corrected my answer and added the i modifier too. Thanks!
@Alex coady - It does. I misunderstood your question but copy the line above and try it again.
Cheers @francois - I can't accept yours as the right answer for another 6 minutes though...
2

How about

$this->permalink = preg_replace('/\W/i', '-', $this->permalink);

\W is any non-word character (letter, number, underscore)

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.