简体   繁体   中英

How to replace 3 words coming from mysql to links

I have a table which contains one row with a string (for example: 'me', 'you', 'him') and now when I fetch them with PHP I want to replace them with links,

I tried with explode to seperate them and then add links but its not going really well, I started to make a function but it didn't go really well. Can you guys help me to make a function to fetch a string, and then seperate those 3 words and add a certain link for each one of them. the links already exist I just want to replace those words with them.

WARNING: not every row has those 3 words, some have ony the first word some have all of the 3 words.. etc.!

Try strtr() with array argument.

http://php.net/manual/en/function.strtr.php

I'm not sure exactly what you're asking but I think something along these lines might help:

function replace_you_me_him($string) {
    $new_string = str_replace(
        array(
            'me',
            'you',
            'him',

            'Me',
            'You',
            'Him'
        ),
        array(
            '<a href="me.html">me</a>',
            '<a href="you.html">you</a>',
            '<a href="him.html">him</a>',

            '<a href="me.html">Me</a>',
            '<a href="you.html">You</a>',
            '<a href="him.html">Him</a>'
        ),
        $string
    );
    return $new_string;
}

$s = "You, me and him went for a walk.<br/>";
echo replace_you_me_and_him($s);
//<a href="you.html">You</a>, <a href="me.html">me</a> and <a href="him.html">him</a> went for a walk.<br/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM