user2738640
user2738640

Reputation: 1227

match content with preg_match_all

I want to get the titles text from the following $content into an array. So I'm trying to use preg_match_all, however I'm making some mistake in the expression, because it does not select the title correctly.

$content = '[sc-item title="Item1 Title"] Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum scelerisque posuere euismod. P [/sc-item][sc-item title="Item2 Title"] Lorem [/sc-item]';

$titles = array();
preg_match_all( '/sc-item title=\"([^\']+)\"/i', $content, $matches, PREG_OFFSET_CAPTURE );

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

In the above example, I want to get the text Item1 Title and Item2 Title.

Upvotes: 0

Views: 36

Answers (2)

Kazeko
Kazeko

Reputation: 36

Try this pattern

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

? means non-greedy; or use modifier

preg_match_all( '/sc-item title="([^\']+)"/iU', $content, $matches, PREG_OFFSET_CAPTURE );

It has the same result.

By the way, I think double quote escape is unnecessary.

Upvotes: 1

Manolo
Manolo

Reputation: 26460

Add the g flag:

preg_match_all( '/sc-item title=\"([^\']+)\"/ig', $content, $matches, PREG_OFFSET_CAPTURE );

Upvotes: 1

Related Questions