简体   繁体   中英

Regular expressions in PHP / find “<a> </a>”

I want to check a textarea. If the user enter some links in the textarea, php should automatically tag the links. I'm using this code:

    $message = "text with some link within"; 

    $url = '@(?!<a[^>]*?>)(http)?(s)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])(?![^<]*?</a>)@';


    if(preg_match($url, $message) == 1){

    $message = preg_replace($url, '<a href="http$2://$4" target="_blank" rel="nofollow" title="$0">$0</a>', $message);

    }

The problem is, when there's already a tagged link (with an "a" tag), regex is destroying the link.

Here is an example:

first input from textarea: Hello .... test.com

changed by regex: Hello ... <a href="http://test.com" target="_blank" rel="nofollow" title="test.com">test.com</a>

this is working fine, but if you update this:

Hello ... http://test.com" target="_blank" rel="nofollow" title="test.com" target="_blank" rel="nofollow" title="test.com">test.com">test.com">test.com

Thanks for your help!

I'm not familiar with PHP and maybe this is not a good pattern for url validation, but the point is if there is already an "a" tag, the text is not replaced.

<?php

    $message = array(
        'Hello ... <a href="http://test.com" target="_blank" rel="nofollow" title="test.com">test.com</a>',
        "Hello .... http://www.test.com ..."
    );

    $url = '@(<a[^>]*>[^<]+</a>|((https?://)?[\w\.-]+\.[a-zA-Z]{2,3}[^\s\W]*))@';

    foreach ($message as $msg) {

        preg_match($url, $msg, $matches);

        if(preg_match($url, $msg) == 1 && count($matches) > 2) {

            $msg = preg_replace($url, '<a href="$0" target="_blank" rel="nofollow" title="$0">$0</a>', $msg);

        }

        echo $msg.PHP_EOL;

    }

    // Output:
    // Hello ... <a href="http://test.com" target="_blank" rel="nofollow" title="test.com">test.com</a>
    // Hello .... <a href="http://www.test.com" target="_blank" rel="nofollow" title="http://www.test.com">http://www.test.com</a> ...

Hope it helps.

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