1

I have string like this [1] Name : Bro Jhon<br>[2] Name : Japar S

How to get Bro Jhon and Japar S and echo it?

What I've tried so far

$op = preg_match_all("/Name: (.*?)<br>/g",$x);
2
  • 3
    what you tried so far? Commented Jun 6, 2016 at 6:33
  • i already try $op = preg_match_all("/Name: (.*?)<br>/g",$x); but not work...Please i'm not understand about regex Commented Jun 6, 2016 at 6:34

4 Answers 4

1

Have a try with this:

<?php
$subject = str_replace('<br>', "\n", '[1] Name : Bro Jhon<br>[2] Name : Japar S');
preg_match_all('/Name\s*:\s*(.*)/', $subject, $tokens);
print_r($tokens[1]);

The output obviously is:

Array
(
    [0] => Bro Jhon
    [1] => Japar S
)
Sign up to request clarification or add additional context in comments.

1 Comment

Simple regex! made use of \n. my +1
0

You need to update your regex into

Name\s*:\s*(.*?)(?=\<br\>|$)

Problem with your regex are as follows

Name: (.*?)<br>
  • Within your string you have space between Name & : i.e Name : and your regex is looking for Name: i.e. without space
  • Other one is your regex will match for first value only i.e. before <br> and not for those which're at the end of string
  • Also you don't need to specify g modifier or it'll throw warning for the same
  • preg_match returns value in boolean so for getting matches you need to assign third parameter.

So your PHP code looks like as

preg_match_all("/Name\s*:\s*(.*?)(?=\<br\>|$)/",$str,$n);
print_r($n[1]);

Comments

0

You could try to split the complete string. Something like:

<?
    $str = "[1] Name : Bro Jhon<br>[2] Name : Japar S";
    //splits for each <br>
    $splitted_values = split("<br>", $str);
    //on each splitted string
    foreach($splitted in $splitted_values){
        //we obtainwhete the : is
        $pos = strpos(":", $splitted);
        //the we remove from left to right
        $name = substr($splitted, $pos);
        //some spaces are removed also
        $name = trim(name);
        //finally the echo
        echo $name;
    }
?>

Also, you could write a regular expression.

Comments

0

We can extract word like this,Sorry I am quite poor with recuring function.I hope this will help you.

function getWord_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

$fullstring = '[1] Name : Bro Jhon<br>[2] Name : Japar S';
$parsed = getWord_between($orgstring, 'Name :', '<br>');

echo $parsed;

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.