2

Here I have a string, "Hello World! I am trying out regex in PHP!". What I want to do is retrieve string values between a set of characters. In this example, the characters are ** **

$str = "**Hello World!** I am trying out regex in PHP!";
preg_match('#\*\*(.*)\*\*#Us', $str, $match);
echo $match[1];

This will echo out "Hello World!", but I want to echo out several matches:

$str = "**Hello World!** I am trying out **regex in PHP!**";

How would I be able to do so? I tried using preg_match_all() but I don't think I was using it properly, or that it would work at all in this case.

3 Answers 3

2

You can use:

$str = "**Hello World!** I am trying out **regex in PHP!**";
preg_match_all('/\*{2}([^*]*)\*{2}/', $str, $m);

print_r($m[1]);
Array
(
    [0] => Hello World!
    [1] => regex in PHP!
)

Even your regex #\*\*(.*)\*\*#Us should work with this but my suggested regex is little more efficient due to negation based pattern [^*]*

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

Comments

2

You got 1 match owing to using preg_match.You should use preg_match_all Here is another pattern.It uses word non word match between the delimiters

<?php
    $str = "**Hello World!** I am trying out **regex in PHP!**";
    $regex='/\*\*([\w\W]*)\*\*/iU';
    preg_match_all($regex, $str, $m); 
    print_r($m[1]);

1 Comment

Which part of your regex is benefiting from that i pattern modifier?
1

I suggest you to use a non-greedy form of regex. Because i think you want to match also the contents (text inside **) where the single * resides.

$str = "**Hello World!** I am trying out **regex in PHP!**";
preg_match_all('~\*\*(.*?)\*\*~', $str, $matches);
print_r($matches[1]);

DEMO

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.