user2738640
user2738640

Reputation: 1227

PHP match content

I have following $content string. I has title and optionally the icon values also. I want to get all the values of titles, but I want to check there is an icon for that title, then I want to get that also.

I can get all titles using the preg_match_all. However I am unable to find out how can I check if there's icon for that, and display it.

I'm trying following code:

$content = '[sc-item title="Item1 Title" icon="icon-bullet"] Lorem ipsum dolor sit amet[/sc-item][sc-item title="Item2 Title"] Lorem [/sc-item]';

$titles = array();
preg_match_all( '/sc-item title="(.*?)"/i', $content, $matches, PREG_OFFSET_CAPTURE );
preg_match_all( '/icon="(.*?)"/i', $content, $icon_matches, PREG_OFFSET_CAPTURE );

if( isset($matches[1]) ){ 
    $titles = $matches[1]; 
}

if( isset($icon_matches[1]) ){ 
    $icons = $icon_matches[1]; 
}

foreach( $titles as $title ){
    echo $title[0];
    //echo $icon[0];
}

In the above example, the first title has and icon next to it, while the second title does not. So I will like to get the first title+icon and second title only.

Upvotes: 0

Views: 112

Answers (1)

TiMESPLiNTER
TiMESPLiNTER

Reputation: 5889

Use this regex:

preg_match_all('/sc-item title="(.*?)"\s+(?:icon="(.*?)")?/i', $content, $matches);

to achieve what you wan't. It's a combination of your two regexes about.

Explenation for(?:...)?

  • (?:...) defines a none catchable group (does not appear in the result array $matches)
  • ? at the end means it's optional.

If strlen($matches[$i][2]) is equal to 0 there is no icon.

But I suggest to you that you first match all sc-items and then parse their attributes. So you are more flexible with the order of the attributes:

$content = '[sc-item icon="icon-bullet" title="Item1 Title" other="false"] Lorem ipsum dolor sit amet[/sc-item][sc-item title="Item2 Title"] Lorem [/sc-item][sc-item title="Item3 Title" icon="icon-bullet"] Lorem [/sc-item]';

preg_match_all('/\[sc-item(.+?)\]/i', $content, $matches);

echo'<pre>'; //var_dump($matches);

foreach($matches[1] as $m) {
    $attrs = getAttributes($m);

    var_dump($attrs);
}

function getAttributes($attrsAsStr) {
    preg_match_all('/\s*(.+?)\s*=\s*"(.+?)"/', $attrsAsStr, $attrs, PREG_SET_ORDER);

    $attrsArr = array();

    foreach($attrs as $attr) {
        $attrsArr[$attr[1]] = $attr[2];
    }

    return $attrsArr;
}

Upvotes: 1

Related Questions