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

Identify a link from html using PHP regular expressions

  • Hi,

    I'm developing a wordpress theme, and I want to extract all the HTML Links (hrefs) with the extension of MP3 into my side bar. I know the wordpress functions to get posts, etc. What I want to know is how to use PHP regular expressions to get a link for an .mp3 that exist as a link from a string variable.

    For example suppose the string is,

    $mystring= \"<p> Hello this is a WP post. <a href=\"somefile.mp3\">Here is a link to mp3<a/> </p> \";


    I want to be able to have a function which returns "somefile.mp3" However, I want only the links with a particular extenstion (e.g. .mp3) to be returned and not merely all the href links.

    I'm a bit of a noob when it comes to PHP regular expressions, Any help would be much appreciated.

    Thanks,
    Deane.
  • http://php.net/preg_match

    The regular expression should be something like:
    /^(([A-Za-z0-9\-_]+)\.(mp3))+/


    Try experimenting with the regex to get what you want (this would be a very helpful tool).

    [code=php]<?php
    $mystring 
    = '<p> Hello this is a WP post. <a href="somefile.mp3">Here is a link to mp3</a></p>';

    preg_match('/^(([A-Za-z0-9\-_]+)\.(mp3))+/', $mystring, $matches);

    var_dump($matches); ?>[/code]
  • Have a look at http://blog.themeforest.net/screencasts/a-crash-course-in-regular-expressions/ screen cast or the series http://blog.themeforest.net/screencasts/regular-expressions-for-dummies/ from the Theme Forest blog for great tutorials on Regular expressions.
    Matt