简体   繁体   中英

How can I extract string using Php regular expression

I have string like <p>{{name}}</p> and I tried below code:

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

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>{{\\K.+?(?=}}<\\/p>)

Explanation

  • Match <p>{{
  • Reset the starting point of the reported match \\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>

You can use preg_match_all to find all of the matches, or use preg_match to return the first 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 .

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

<?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

You will get array of values inside {{...}}

Array
(
    [0] => name
    [1] => age
)

You can use strip_tags and then preg_replace

$subject="<p>{{name}}</p>";
$pattern="/[^a-zA-Z]/";
$result = preg_replace($pattern, "", strip_tags($subject));

Output will be name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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