Amir Gheybi Amir Gheybi - 5 months ago 23
jQuery Question

Convert Certain Characters to HTML Link

I have a string like this

"hello my #old good #friends"


I want certain words such as (#example) to be converted to HTML links

"hello my <a href='example.com/tags/old'>old</a> good <a href='example.com/tags/friends'>friends</a>"


Thanks

sorry for my english

Answer

Using PHP without Regular expression

    $string = "hello my #old good #friends";
    $new_string=[];
    $new_string = explode(' ', $string);

    foreach ($new_string as $key => $value) {
        $space = 0 === $key ? '' : ' ';
        if ('#' === $value[0]) {
            $n_str=  str_replace("#", '', $value);
            echo "$space<a href='example.com/tags/$n_str'>$n_str</a> ";
        } else {
            echo $space . '' . $value;
        }
    }

html Output

hello my <a href='example.com/tags/old'>old</a> good <a href='example.com/tags/friends'>friends</a>
Comments