realph
realph

Reputation: 4671

Extract <span> tag contents in PHP

Say I have a WordPress post, and certain words are wrapped in span tags.

For example:

<p>John went to the <span>bakery</span> today,
and after picking up his favourite muffin
he made his way across to the <span>park</span>
and spent a couple hours on the <span>swings</span>
with his friends.</p>

Is then then a way using PHP to dynamically spit them (the words in the span tags) out as an ordered list in my template file?

Like so:

<h3>What John Did Today</h3>
<ol>
<li>bakery</li>
<li>park</li>
<li>swings</li>
</ol>

If someone could point be in the right direction of how to do something like this, it would be much appreciated. Thank you.

Upvotes: 2

Views: 268

Answers (4)

Jason Rogers
Jason Rogers

Reputation: 97

I'm not a regex whiz but this SHOULD do the job for replacing <span> tags with <li> tags:

$str = preg_replace("/<span>([^[]*)<\/span>/i", "<li>$1</li>", $str);

..i know this doesn't directly answer your question but it should help you with this at some point lol

EDIT: full actually working regex solution for getting all your span tags into an array and converting to list items at the same time:

// input string:
$str = '<span>Walk</span> blah <span>Drive</span> blah blee blah <span>Eat</span>';

// get array of span matches
preg_match_all("/(<span>)(.*?)(<\/span>)/i", $str, $matches, PREG_SET_ORDER);

// build array using the exact matches
foreach($matches as $val){
    $spanArray[] = preg_replace("/<span>([^[]*)<\/span>/i", "<li>$1</li>", $val[0]);
}

if you then print_r($spanArray); you should get something that looks like this:

Array
(
    [0] => <li>Walk</li> 
    [1] => <li>Drive</li> 
    [2] => <li>Eat</li> 
)

Upvotes: 0

Matthew
Matthew

Reputation: 48284

$str = '<p>John went to the <span>bakery</span> today, and after picking up his favourite muffin     he made his way across to the <span>park</span> and spent a couple hours on the <span>swings</span> with his friends.</p>';

$d = new DomDocument;
$d->loadHTML($str);

$xpath = new DOMXPath($d);
echo "<h3>What John Did Today</h3>\n";
echo "<ol>\n";
foreach ($xpath->query('//span') as $span)
  echo "<li>".$span->nodeValue."</li>\n";
echo "</ol>\n";

Upvotes: 5

Spyros
Spyros

Reputation: 48626

Parse the DOM :

http://simplehtmldom.sourceforge.net/

Upvotes: 0

Wanderson Silva
Wanderson Silva

Reputation: 1199

A simple possibility is using regular expressions, take a look at preg_match function

Upvotes: 0

Related Questions