Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression in PHP preg_replace() yields empty results

I'm struggling with the regular expression syntax needed to simply transform this string:

posts/2012-03-16-23-07_an-awesome-post.md

into this string:

an-awesome-post

using the preg_replace() PHP function. Here's what I've got so far:

preg_replace('posts/[0-9-]*_([a-z-]*).md', '$1', 'posts/2012-03-16-23-07_an-awesome-post.md');

No dice. When I assign the result to a variable and echo() out that variable, I get nothing. My regex syntax is a bit rusty, but Googling around a bit makes me think that, at the very least, I'm on the right track.

like image 438
Sam Avatar asked Mar 14 '26 05:03

Sam


1 Answers

The regex needs to be surrounded by delimiters.

Try '#posts/[0-9-]*_([a-z-]*).md#' as your $pattern (using '#' as the delimiter).

Also, do you want that . to match a literal dot? Then it has to be escaped by a backslash, as in \..

like image 136
mathematical.coffee Avatar answered Mar 16 '26 19:03

mathematical.coffee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!