简体   繁体   中英

PHP: Leftover text in Regular Expression

Trying to write a script where a user inputs [link](http://www.example.com) and gets back a hyperlink named "link" with "http://www.example.com" as the href. Here's my code:

if(preg_match("/\[[a-zA-Z0-9]*\]([a-zA-Z0-9]*)/", $input))
{
    $input = preg_replace("/\[([a-zA-Z0-0-9]*)\](([a-zA-Z0-9]*))/", "<a href='$2'>$1</a>", $input);
}

What I keep getting back is [link](http://www.example.com)(http://www.example.com) . Any idea what I'm doing wrong?

You forgot to escape the literal parentheses (therefore the (([a-zA-Z0-9]*)) part simply matched the empty string).

Also, you'll need to allow at least slashes, colons and dots if you want to match links:

$input = preg_replace("%\[([A-Z0-9]*)\]\(([A-Z0-9/:.]*)\)%i", "<a href='$2'>$1</a>", $input);

or possibly

$input = preg_replace("%\[([A-Z0-9]*)\]\((https?://[A-Z0-9/.]*)\)%i", "<a href='$2'>$1</a>", $input);

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