用于删除<>和 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.

http://regex101.com/r/vF0kU2/5

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);

DEMO

\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();