Preg_replace 在所有字符之间添加不需要的 space
Preg_replace adds unwanted space between ALL characters
我有来自 HTML table 的输入。
首先用'_'替换想要的间距。然后用间距替换 HTML 标签,这样我就可以按列提取信息。
我希望我的输出是:
100 Request_in_progress Pending_response 789653686
Instead the output adds extra spacing like this
$testString = '<tr><td>100</td><td>Request in progress</td><td></td><td></td><td>Pending response</td><td>789653686</td><td></td><td></td><td></td></tr>';
$rmSpace = str_replace(' ', '_', $testString);
$tags = '(<td>||</td>||<tr>||</tr>||<th>||</th>)';
$result = preg_replace($tags, ' ', $rmSpace);
echo $result;
如何使用简单 DOMDocument
实现此目的的示例
$testString = '<tr><td>100</td><td>Request in progress</td><td></td><td></td><td>Pending response</td><td>789653686</td><td></td><td></td><td></td></tr>';
$dom=new DOMDocument;
$dom->loadHTML( $testString );
$col=$dom->getElementsByTagName('td');
$out=array();
if( $col->length > 0 ) foreach( $col as $node )$out[]=str_replace(' ','_',$node->nodeValue);
$out=array_filter($out);
echo implode(' ',$out);
这是因为 regex
不正确。
在正则表达式中,the vertical bar (|
) 连接备选路径。
表达式 <td>||</td>
表示“<td>
OR 空字符串 OR </td>
”(依此类推,但其余的已经没有了没关系)。
因此,您的 regex
匹配它包含的所有 HTML 标签,但它也匹配输入字符串中任意两个连续字符之间的空字符串。
正确的 regex
是 <td>|</td>|<tr>|</tr>|<th>|</th>
。
$tags = '#<td>|</td>|<tr>|</tr>|<th>|</th>#';
$result = preg_replace($tags, ' ', $rmSpace);
我有来自 HTML table 的输入。 首先用'_'替换想要的间距。然后用间距替换 HTML 标签,这样我就可以按列提取信息。
我希望我的输出是:
100 Request_in_progress Pending_response 789653686
Instead the output adds extra spacing like this
$testString = '<tr><td>100</td><td>Request in progress</td><td></td><td></td><td>Pending response</td><td>789653686</td><td></td><td></td><td></td></tr>';
$rmSpace = str_replace(' ', '_', $testString);
$tags = '(<td>||</td>||<tr>||</tr>||<th>||</th>)';
$result = preg_replace($tags, ' ', $rmSpace);
echo $result;
如何使用简单 DOMDocument
$testString = '<tr><td>100</td><td>Request in progress</td><td></td><td></td><td>Pending response</td><td>789653686</td><td></td><td></td><td></td></tr>';
$dom=new DOMDocument;
$dom->loadHTML( $testString );
$col=$dom->getElementsByTagName('td');
$out=array();
if( $col->length > 0 ) foreach( $col as $node )$out[]=str_replace(' ','_',$node->nodeValue);
$out=array_filter($out);
echo implode(' ',$out);
这是因为 regex
不正确。
在正则表达式中,the vertical bar (|
) 连接备选路径。
表达式 <td>||</td>
表示“<td>
OR 空字符串 OR </td>
”(依此类推,但其余的已经没有了没关系)。
因此,您的 regex
匹配它包含的所有 HTML 标签,但它也匹配输入字符串中任意两个连续字符之间的空字符串。
正确的 regex
是 <td>|</td>|<tr>|</tr>|<th>|</th>
。
$tags = '#<td>|</td>|<tr>|</tr>|<th>|</th>#';
$result = preg_replace($tags, ' ', $rmSpace);