简体   繁体   English

关闭不完整的href标签

[英]Close incomplete href tag

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? 如何修复不完整的href标签? 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. 我不想使用strip_tags()htmlentities()因为我希望它显示为工作链接。

Not really good at regex but you can do a workaround using DOMDocument . 不是很擅长正则表达式,但你可以使用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. 只需在从mysql中提取数据时修改数据。 Add to your code that gets the data from mysql something like: 添加到从mysql获取数据的代码:

...
$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: 您表示您可能对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'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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM