treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Is This Possible?

  • Okay, so say I have a WordPress post, and certain words are wrapped in a 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.
  • The coding's pretty involved, but you could use the preg_replace() function to search for a strings matching
    <span>whatever</span>
    and then output the matches in the format you want. The function description is here: http://www.php.net/manual/en/function.preg-replace.php
  • You can use regular expression(use preg_match/preg_match_all to match anything you want)

    In your given string, it can be done something like this:

    <?php
    $data='<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>';
    preg_match_all('#<span[%>]*>(.*)</span>#Uis',$data,$matches,PREG_SET_ORDER);
    echo '<h3>What John Did Today</h3>';
    echo '<ol>';
    foreach($matches as $match)
    {
    echo '<li>'.$match[1].'</li>';
    }
    echo '</ol>';


    Read more on PHP manual: http://www.php.net/manual/en/function.preg-match-all.php
  • Thanks @ddliu! Something like that is exactly what I was looking for.
  • Does anyone know how would I go about this, I'm using WordPress and I want to echo img title's in that ordered list? I want img titles to be my $data for instance.
  • Well, it could all be done with regular expression as I've showed.

    If you know some JQuery, you can also do it on client side.

    And in my opinion, the best way is to use phpQuery if you want to parse HTML on server side.