Reputation: 39
I want to match the following string with a regular expression:
$string ="test string [% code content ='test content' class ='myclass' %]";
I want to extract the class and content from this string in percentage braces. Iam using this pattern for matching
$regex_pattern = "/[% ?.*](.*)[\/%]/";
preg_match_all($regex_pattern,$content,$matches);
but not getting the output that I require.
Upvotes: 0
Views: 51
Reputation: 626861
You can use the regex to capture contents
and class
values regardless of their positions inside the [% ... %]
:
(?:content|class)\s*='([^']+?)'(?=(?:(?!\[\%|\%\]).)*?\%\])
See demo.
<?php
$re = "/(?:content|class)\\s*=\\s*'([^']+?)'(?=(?:(?!\\[\\%|\\%\\]).)*?\\%\\])/";
$str = "test string [% code content ='test content' class ='myclass' %]";
preg_match_all($re, $str, $matches);
echo $matches[1][0] . "\n";
echo $matches[1][1] . "\n";
?>
Here is a sample program.
Output:
test content
myclass
Upvotes: 1
Reputation: 174706
Here you need to use \G
anchor since you're trying to grab some contents from a block [%..%]
.
(?:\[%|(?<!^)\G).*?(content|class)\s*='([^']*)'(?=(?:(?!\[%|%\]).)*?%])
Example:
$s = "content ='outside content' test string [% code content ='test content' class ='myclass' %]";
preg_match_all("~(?:\[%|(?<!^)\G).*?\K(content|class)\s*='([^']*)'(?=(?:(?!\[%|%\]).)*?%])~", $s, $matches);
print_r($matches);
Output:
Array
(
[0] => Array
(
[0] => content ='test content'
[1] => class ='myclass'
)
[1] => Array
(
[0] => content
[1] => class
)
[2] => Array
(
[0] => test content
[1] => myclass
)
)
Upvotes: 1