[英]How can I extract string using Php regular expression
I have string like <p>{{name}}</p>
and I tried below code: 我有类似
<p>{{name}}</p>
这样的字符串,并且尝试了以下代码:
$subject="<p>{{name}}</p>";
$pattern="/(\[\[|<p>{{)\w+(]]|}}</p>)/";
$success = preg_match($pattern, $subject, $match);
if ($success) {
$str = substr($match[0], 5,-2);
echo $str;
} else {
echo 'not match';
}
How can I extract name
value using regex function. 如何使用正则表达式函数提取
name
值。
If you are looking for name between a <p>
tags and double opening and closing curly braces {{ }}, you could also do it like this: 如果您要在
<p>
标记之间以及双大括号{{}}之间寻找名称,则也可以这样:
Explanation 说明
<p>{{
<p>{{
\\K
\\K
(?=}}<\\/p>)
which asserts that what follows is }}</p>
(?=}}<\\/p>)
断言其后是}}</p>
You can use preg_match_all to find all of the matches, or use preg_match to return the first match. 您可以使用preg_match_all查找所有匹配项,或使用preg_match返回第一个匹配项。
Your code could look like: 您的代码可能如下所示:
$subject="<p>{{name}}</p>";
$pattern="/<p>{{\K.+?(?=}}<\/p>)/";
$success = preg_match($pattern, $subject, $match);
if ($success) {
$str = substr($match[0], 5,-2);
echo $str;
} else {
echo 'not match';
}
Note that $str
will be false
in this case using substr . 请注意,在这种情况下,使用substr将
$str
为false
。
No need to check p
tag as you want only text inside {{...}}
.If you want to get all value inside {{..}}
try preg_match_all
like this 无需检查
p
标记,因为您只想在{{...}}
内输入文本。如果要在{{..}}
内获取所有值,请尝试preg_match_all
这样
<?php
$subject="<p>name is {{name}} and age is {{age}}</p>";
preg_match_all('#\{\{(.*?)\}\}#', $subject, $match);
print_r($match[1]);
?>
Live demo : https://eval.in/929064 现场演示: https : //eval.in/929064
You will get array of values inside {{...}}
您将在
{{...}}
获得值数组
Array
(
[0] => name
[1] => age
)
You can use strip_tags and then preg_replace 您可以使用strip_tags然后使用preg_replace
$subject="<p>{{name}}</p>";
$pattern="/[^a-zA-Z]/";
$result = preg_replace($pattern, "", strip_tags($subject));
Output will be name
输出将是名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.