Search code examples
phpregexstringpreg-match

How to select first bold words from sentence by php?


I want to select first bold words from sentence.

If my sentence is <b>My username here</b> Address: <b>Bangladesh.</b> Mobile: <b>xxxxxx</b>

Here I want to output just: My username here

I read about preg_match, explode but cannot understand how to apply them.


Solution

  • For only first bold section then use below code.

    <?php
    $text = '<b>My username here</b> Address: <b>Bangladesh.</b> Mobile: <b>xxxxxx</b>';
    preg_match("'<b>(.*?)</b>'si", $text, $match);
    
    echo $match[0];
    ?>
    

    for all bold search use this

    <?php
    $text = '<b>My username here</b> Address: <b>Bangladesh.</b> Mobile: <b>xxxxxx</b>';
    preg_match_all("'<b>(.*?)</b>'si", $text, $match);
    
    foreach($match[1] as $val)
    {
        echo $val.' ';
    }
    ?>
    

    Here is the sample