The_Perfect_Username
The_Perfect_Username

Reputation: 73

Using regex in php to find string values between characters multiple times

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.

Upvotes: 2

Views: 1736

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174696

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

Upvotes: 1

rahulinaction
rahulinaction

Reputation: 354

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]);

Upvotes: 2

anubhava
anubhava

Reputation: 784998

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 [^*]*

Upvotes: 2

Related Questions