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
453 views
in Technique[技术] by (71.8m points)

preg replace - automatic convert word to link in PHP

I want write a simple code that convert special words to special link (for wiki plugin), if it's not a link!

For example suppose we have a text "Hello! How are you?!" and
we want convert are to <a href="url">are</a>, but if we have <a href="#"> Hello! How are you</a>?! or Hello! <a href="url">How are you?!</a> does not change. Because it's a link.

How can I do it in PHP?! With preg_replace?! How to?

Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It's easy.

<?php

$string = "Hello! How <a href="#">are</a> you?!";
$stringTwo = "Hello! how are you?!";

function turnTheWordIntoALink($string, $word, $link) {
    if(isLink($string)) {
        return $string;   
    } else {
        $string = str_replace($word, "<a href="" . $link . "">" . $word . "</a>", $string);
        return $string;
    }
}

function isLink($string) {
    return preg_match("/(<a href=".">)/", $string);
}

echo turnTheWordIntoALink($string, 'are', 'http://google.com');
echo turnTheWordIntoALink($stringTwo, 'are', 'http://google.com');

Output:

First function output: Hello! How <a href="#">are</a> you?!

Second function output: Hello! how <a href="http://google.com">are</a> you?!


Alternative:

If you want to not detect <a> tags which were closed, you can use this alternative code:

$stringThree = "Hello! how <a href="#">are you?!";

function turnTheWordIntoALink($string, $word, $link) {
    if(isLink($string)) {
        return $string;   
    } else {
        $string = str_replace($word, "<a href="" . $link . "">" . $word . "</a>", $string);
        return $string;
    }
}

function isLink($string) {
    return preg_match("/(<a href=".">)+(.)+(</a>)/", $string);
}

echo turnTheWordIntoALink($stringThree, 'are', 'http://google.com') . "
";

This gives the output: Hello! how <a href="#"><a href="http://google.com">are</a> you?!


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

...