0

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.

4 Answers 4

3

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
)
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.