Close incomplete label href

I am trying to close a line like this:

$link = 'Hello, welcome to <a href="www.stackoverflow.com';

echo $link;

How to fix an incomplete href tag? I want this to be:

$link = 'Hello, welcome to <a href="www.stackoverflow.com"></a>'; // no value between <a> tag is alright.

I do not want to use strip_tags()or htmlentities(), because I want it to appear as a working link.

+4
source share
3 answers

Not very 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>
+3
source

Just change the data when you pull it out of mysql. Add to your code that receives data from mysql something like this:

...
$link = < YOUR MYSQL VALUE > . '"></a>';
...

Or you can run a query in your database to update the values ​​by adding the line:

"></a>
0
source

, Regex, :

$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 a match, close the <a> tag
if ($isMatch) {
    $link .= '"></a>';
}

// Output the result
echo $link;

:

Hello, welcome to <a href="www.stackoverflow.com"></a>
0

All Articles