2

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.

5 Answers 5

7

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 \..

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

1 Comment

You are a god. Thanks! And for those interested in the resulting pattern, it's: '#posts/[0-9-]*_([a-z-]*)\.md#'
1
preg_replace('/posts\/[0-9-]*_([a-z-]*)\.md/', '$1', 'posts/2012-03-16-23-07_an-awesome-post.md');

Comments

1

can you expect the string before "an-awesome-post" always to be the same lenght? And the extension always to be .md?

If so, you can just count the number of chars before and after and cut them away.

For Example:

$string = substr($string, 23);
$string = substr($string, 0, -3);

Comments

1
<?php
$str="posts/2012-03-16-23-07_an-awesome-post.md";
$pattern=array('/([^_]*_)/','/\.md/');
$replacement=array('','');
echo preg_replace($pattern, $replacement, $str);

?>

Comments

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

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.