Php 正则表达式在html属性中查找子字符串

Php 正则表达式在html属性中查找子字符串,php,regex,Php,Regex,我需要一个正则表达式来查找输入标记的数据属性标记内的所有标记 注意:页面中可能有我不想包含的其他标记(属性之外),因此正则表达式应该只在数据内容属性内部提取数据 谢谢 试试这个regex'/data content=\“***\”/imsU'我在评论部分的警告,你可以使用preg\u replace\u callback()和str\u replace()的组合: $str=''; $regex='/data content=“([^”]*)/i'; $str=preg\u replace\u回

我需要一个正则表达式来查找输入标记的数据属性标记内的所有

标记

注意:页面中可能有我不想包含的其他

标记(属性之外),因此正则表达式应该只在数据内容属性内部提取数据


谢谢

试试这个regex
'/data content=\“***\”/imsU'
我在评论部分的警告,你可以使用
preg\u replace\u callback()
str\u replace()
的组合:

$str='';
$regex='/data content=“([^”]*)/i';
$str=preg\u replace\u回调($regex,
函数($matches){
返回str_replace(数组('
','
'),''$matches[0]); }, $str); echo$str; //输出:
那么它的作用是:在
数据内容
之后用双引号匹配所有内容,并用



再次,最好使用解析器或
xpath
方法(看看这里,有很多很好的答案)。

我认为您不需要,也不应该使用正则表达式。目前还不清楚您希望如何处理找到的换行符,但这应该为您提供一个解析器的起点

$str = '<input data-content="This is a text string with a <br /> inside of it" />';
$regex = '/data-content="([^"]*)/i';
$str = preg_replace_callback($regex,
    function($matches) {
        return str_replace(array('<br/>', '<br />'), '', $matches[0]);
    },
    $str);
echo $str;
// output: <input data-content="This is a text string with a  inside of it" />
$string='1!'
';
$doc=新的DOMDocument();
$doc->loadHTML($string);
$inputs=$doc->getElementsByTagName('input');
foreach($inputs作为$input){
preg_match_all('/',$input->getAttribute('data-content'),$linebreaks);
打印(换行符);
}

根据您想做什么,所有的匹配可能是必要的,也可能不是。重要的一点是,
$input->getAttribute('data-content')
将为您提供所需的数据/属性字符串。

不要。为此使用一个新的方法。此外,这个问题的变化已经被证实,我知道最佳实践,但我仍然需要做到这一点。假设我只想在子字符串中找到一个子字符串。同样的概念…现在,是的,它们都是输入。虽然主常量是
数据内容
属性,但据我所知,它在其他任何地方都没有使用。如果它包含
,它只会在标记之间查找整个字符串。不是我需要的=/此正则表达式丢弃页面中的所有其他
,只需将捕获组添加到此正则表达式即可更新答案以包含您的建议?此正则表达式存在许多问题。您应该重写或删除此答案。是否将其与preg_replace()一起使用?如果是这样,您可以尝试
preg\u replace('/(数据内容=\“*)()(.*\”)/imsU',$1{somereplacement}$3,$html)。问题是,如果
数据内容
属性中有超过1个
的内容,它将无法正常工作
$str = '<input data-content="This is a text string with a <br /> inside of it" />';
$regex = '/data-content="([^"]*)/i';
$str = preg_replace_callback($regex,
    function($matches) {
        return str_replace(array('<br/>', '<br />'), '', $matches[0]);
    },
    $str);
echo $str;
// output: <input data-content="This is a text string with a  inside of it" />
$string = '<div>
  <input data-content="This is a text string with a <br /> inside of it" />
</div>';
$doc = new DOMDocument();
$doc->loadHTML($string);
$inputs = $doc->getElementsByTagName('input');
foreach($inputs as $input) {
    preg_match_all('/<br\h*\/?>/', $input->getAttribute('data-content'), $linebreaks);
    print_r($linebreaks);
}