Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hi I have placeholder text in my content from the CMS like this:

$content = "blah blah blah.. yadda yadda, listen to this:
{mediafile file=audiofile7.mp3}
and whilst your here , check this: {mediafile file=audiofile24.mp3}"

and i need to replace the placeholders with some html to display the swf object to play the mp3.
How do i do a replace that gets the filename from my placeholder.

I think the regx pattern is {mediafile file=[A-Za-z0-9_]} but then how do i apply that to the whole variable containing the markers?

Thanks very much to anyone that can help,

Will

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
283 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here is a quick example, using preg_replace_all, to show how it works :

if $content is declared this way :

$content = "blah blah blah.. {mediafile file=img.jpg}yadda yadda, listen to this:
{mediafile file=audiofile7.mp3}
and whilst your here , check this: {mediafile file=audiofile24.mp3}";

You can replace the placeholders with something like this :

$new_content = preg_replace_callback('/{mediafile(.*?)}/', 'my_callback', $content);
var_dump($new_content);

And the callback function might look like this :

function my_callback($matches) {
    $file_full = trim($matches[1]);
    var_dump($file_full);       // string 'file=audiofile7.mp3' (length=19)
                                // or string 'file=audiofile24.mp3' (length=20)
    $file = str_replace('file=', '', $file_full);
    var_dump($file);            // audiofile7.mp3 or audiofile24.mp3

    if (substr($file, -4) == '.mp3') {
        return '<SWF TAG FOR #' . htmlspecialchars($file) . '#>';
    } else if (substr($file, -4) == '.jpg') {
        return '<img src="' . htmlspecialchars($file) . '" />';
    }
}

Here, the last var_dump will get you :

string 'blah blah blah.. <img src="img.jpg" />yadda yadda, listen to this:
<SWF TAG FOR #audiofile7.mp3#>
and whilst your here , check this: <SWF TAG FOR #audiofile24.mp3#>' (length=164)

Hope this helps :-)


Don't forget to add checks and all that, of course ! And your callback function will most certainly become a bit more complicated ^^ but this should give you an idea of what is possible.

BTW : you might want to use create_function to create an anonymous function... But I don't like that : you've got to escape stuff, there is no syntax-highlighting in the IDE, ... It's hell with a big/complex function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...