简体   繁体   English

如何使用Php正则表达式提取字符串

[英]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>标记之间以及双大括号{{}}之间寻找名称,则也可以这样:

<p>{{\\K.+?(?=}}<\\/p>)

Explanation 说明

  • Match <p>{{ 匹配<p>{{
  • Reset the starting point of the reported match \\K 重置报告的比赛的起点\\K
  • Match any character one or more times (this will be the value you are looking for) 一次或多次匹配任何字符(这是您要查找的值)
  • A positive lookahead (?=}}<\\/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返回第一个匹配项。

Output 产量

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$strfalse

Try using a pattern with a capture group which isolates the name you want: 尝试将模式与捕获组一起使用,以隔离所需的名称:

subject="<p>{{name}}</p>";
$pattern="/<p>\{\{([^}]+)\}\}<\/p>/";

$success = preg_match($pattern, $subject, $match);
if ($success) {
    echo $match[1];
} else {
     echo 'not match';
}

Demo 演示

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM