I'm trying to close this kind of string:
$link = 'Hello, welcome to <a href="www.stackoverflow.com';
echo $link;
How to fix the incomplete href tag? I want it to be:
$link = 'Hello, welcome to <a href="www.stackoverflow.com"></a>'; // no value between <a> tag is alright.
I don't want to use strip_tags()
or htmlentities()
because i want it to be displayed as a working link.
Not really good at regex but you can do a workaround using DOMDocument
. Example:
$link = 'Hello, welcome to <a href="www.stackoverflow.com';
$output = '';
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($link);
libxml_clear_errors();
// the reason behind this is the HTML parser automatically appends `<p>` tags on lone text nodes, which is weird
foreach($dom->getElementsByTagName('p')->item(0)->childNodes as $child) {
$output .= $dom->saveHTML($child);
}
echo htmlentities($output);
// outputs:
// Hello, welcome to <a href="www.stackoverflow.com"></a>
Just modify the data as you pull it from mysql. Add to your code that gets the data from mysql something like:
...
$link = < YOUR MYSQL VALUE > . '"></a>';
...
Or you can run a query on your database to update the values, appending the string:
"></a>
You indicated you might be interested in a Regex solution, so here's what I was able to come up with:
$link = 'Hello, welcome to <a href="www.stackoverflow.com';
// Pattern matches <a href=" where there the string ends before a closing quote appears.
$pattern = '/(<a href="[^"]+$)/';
// Perform the regex search
$isMatch = (bool)preg_match($pattern, $link);
// If there's a match, close the <a> tag
if ($isMatch) {
$link .= '"></a>';
}
// Output the result
echo $link;
Outputs:
Hello, welcome to <a href="www.stackoverflow.com"></a>
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.