Input text: Our website is <a href="www.me.com">www.me.com</a>
Output required: Our website is <a href="[x]">[x]</a>
Rule: any url needs to be replaced by [x]. URL might be with http/https or www or simply me.com. The solution needs to be case insensitive
$inputext = "<a href="www.me.com">www.me.com</a>";
$rule ="/(?<!a href=\")(?<!src=\")((http|ftp)+(s)?:\/\/[^<>\s]+)/i";
$replacetext = "[X]";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo($outputext);
Thanks for any suggestions.
Never parse HTML with regular expressions. It might seems like overkill to use a DOM parser for a job like this, but you're guaranteed to avoid problems at some point in the future.
$input = 'Our website is <a href="www.me.com">www.me.com</a>';
$replace = "[x]";
$dom = new DomDocument();
$dom->loadHTML($input, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$a = $dom->getElementsByTagName("a")->item(0);
$a->setAttribute("href", $replace);
$a->textContent = $replace;
echo $dom->saveHTML();
What about this to grab, http/https
and with www
or without www
urls?
<?php
$re = '/(https?:\/\/|(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?)/mi';
$str = 'Our website is <a href="www.me.com">www.me.com</a>';
$subst = '[x]';
$result = preg_replace($re, $subst, $str);
echo $result;
Output: <a href="[x]">[x]</a>
Regex https://regex101.com/r/X4vrOt/2
DEMO: https://3v4l.org/fFhOk
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.