我有这个字符串:
clsfd_registration_4371472
在此
<div class="col-sm-1 hidden-xs text-right" id="clsfd_registration_4371472">
我希望在PHP中使用正则表达式删除最后一个下划线,然后删除7位数序列。
我该怎么办? 以下删除7位数字,但不删除下划线。
^_\d{7}$^
谢谢
答案 0 :(得分:0)
如果您只想删除下划线,请使用:
preg_replace('/(?<=\bid="clsfd_registration)_(?=\d{7}")/', '', $str);
参见演示 here 。
如果您想删除数字,请使用:
preg_replace('/(?<=\bid="clsfd_registration)_\d{7}(?=")/', '', $str);
参见演示 here 。
答案 1 :(得分:-1)
由于ID是唯一的,您只需要:
$html = preg_replace('~\bid\s*=\s*["\']?clsfd_registration\K_[0-9]{7}\b~', '',
$html, 1);
模式细节:
\b # word bounday (border between a char from \w class and another char
id
\s* # possible white character here
=
\s*
["\']? # can have single, double or no quotes at all
clsfd_registration
\K # the \K reset all the match before it
_[0-9]{7}
\b # to be sure that there is not another digit after
另一种方式:
$doc = new DOMDocument();
@$doc->loadHTML($yourhtmlstring);
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//div[contains(@id, "clsfd_registration_")]');
foreach ($nodes as $node) {
$node->setAttribute('id', preg_replace('~_[0-9]{7}$~', '', $node->getAttribute('id'),1));
}
$yourhtmlstring = $doc->saveHTML();