用于删除<>和> PHP中的起始和结束空格的正则表达式
问题描述:
I have a string which have data like this:
<div style="float: right;"><span class='abcd'> test data here </sapn></div>
I want the out put as :
<div style="float: right;"><span class='abcd'>test data here</sapn></div>
So far what I have tried is as in regex php,
preg_replace('/\s+/', '', $data);
preg_replace('/[
]+/', '', $data);
But its not giving me the desired result
答
(<([^ ]+)[^<>]+>)\s*([^<]+?)\s*(<\/\2>)
Try this.Replace by $1$3$4
.See demo.
答
try this
$data = preg_replace('/\s{2,}/', '', $data);
答
You are doing right. But preg_replace
does not modify the argument. rather it returns a modified string
So you can write something like
$data = preg_replace('/\s+/', ' ', $data);
will give $data
as
<div style="float: right;"><span class='abcd'>test data here</sapn></div>
Note
You must replace with a space ' '
so as to preserve a single space
答
You could try the below.
preg_replace('~(?<=<)[^<>]*(?=>)(*SKIP)(*F)|(?:(?<=>)\h+|\h+(?=<))~', '', $data);
\h+
matches one or more horizontal spaces.
答
With DOMDocument:
$html = '<div style="float: right;"><span class="abcd"> test data here </span></div>';
$dom = new DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NODEFDTD|LIBXML_HTML_NOIMPLIED);
$xpath = new DOMXPath($dom);
$textNodeList = $xpath->query('//text()');
foreach ($textNodeList as $textNode) {
$textNode->nodeValue = trim($textNode->nodeValue);
}
$html = $dom->saveHTML();