Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

php - Replacing Placeholder text containing a variable

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...