0

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.

user2738640
  • 1,207
  • 8
  • 23
  • 34

1 Answers1

1

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;
}
TiMESPLiNTER
  • 5,741
  • 2
  • 28
  • 64
  • Thanks a lot for your answer, can you kindly explain a bit more how I can display the title+icon? As in above example I have foreach loop. – user2738640 Nov 11 '13 at 07:51
  • Well I don't know how flexible you have to be. But this won't match elements which looks like: `[sc-item icon="icon-bullet" title="Item1 Title"]` so I give you a better solution, just a moment. – TiMESPLiNTER Nov 11 '13 at 08:00