Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中使用正则表达式匹配字符串_Php_Regex - Fatal编程技术网

在PHP中使用正则表达式匹配字符串

在PHP中使用正则表达式匹配字符串,php,regex,Php,Regex,我是一个初学者,在使用RegExr工具时发现正则表达式有问题 我正在从一个名为properties.XML的XML文件加载一组分类广告的标题,我在这里展示了这个文件- <?xml version="1.0"?> <rss version="2.0"> <channel> <item> <title>For Sale - Toaster Oven</title> </item>

我是一个初学者,在使用RegExr工具时发现正则表达式有问题

我正在从一个名为properties.XML的XML文件加载一组分类广告的标题,我在这里展示了这个文件-

<?xml version="1.0"?>
<rss version="2.0">
  <channel>
    <item>
      <title>For Sale - Toaster Oven</title>
    </item>
    <item>
      <title>For Sale - Sharp Scissors</title>
    </item>
<item>
      <title>For Sale - Book Ends</title>
    </item>
<item>
      <title>For Sale - Mouse Trap</title>
    </item>
<item>
      <title>For Sale - Water Dispenser</title>
    </item>
  </channel>
</rss>

待售-烤面包机烤箱
出售-锋利剪刀
待售-书尾
出售-捕鼠器
待售-饮水机
下面是PHP代码,它解析XML,然后检查是否有匹配项;不幸的是,它没有显示

<?php
$xml = simplexml_load_file("properties.xml");

foreach ($xml->channel->item as $item){
    $title = $item->title;
    $myregex = preg_quote("/(?<=For(.)Sale(.)-(.))[^]+/");
    $result = preg_match($myregex, $title, $trim_title);
    echo $result;
}
?>
channel->item as$item){
$title=$item->title;

$myregex=preg_quote(“/(?您的正则表达式中有一个错误,
[^]
。插入符号用于对方括号中的匹配字符求反。例如,
[^a]
将不匹配a

老实说,你的正则表达式并不理想。如果你只想匹配“待售”字符串后面的内容,我就用它


/出售-([^您可以使用Xpath查询XML文件

$xml = simplexml_load_file("properties.xml");
$results = $xml->xpath('//title/text()');

static $myregex = '/For Sale - (.*)/';
while(list( , $title) = each($results)) {
    $result = preg_match($myregex, $title, $trim_title);
    $trim_title = $trim_title[1];
    echo $result; // Number of matches
    echo $trim_title;
}
更简单的是

while(list( , $title) = each($results)) {
    echo substr($title, 11) . "\n";
}
你可以试试这个

<?php
$xml = simplexml_load_file("properties.xml");

foreach ($xml->channel->item as $item){
    preg_match("/For Sale(.*)<\/title>/siU", $item);
    echo trim($item[1]," -");
}
?>
channel->item as$item){
preg_match(“/待售(.*)/siU”,美元项目);
回音微调($item[1],“-”);
}
?>

问题在于,旧代码无法访问XML元素的text()。谢谢,但我尝试运行此命令,但echo$result仍然返回一组0。很遗憾,谢谢,但它也不起作用-选择整个字符串,而不是“待售”之后的任何字符串“根据需要设置字符串。这是一个来自RegExr的屏幕帽-忘记RegExr中的匹配项或不匹配项-PHP只会为您提供捕获组所需的内容(即括号)。正如@Maks3w指出的,您可能需要访问
text()
,而不是节点本身。您不需要处理结束标记,SimpleXML为您提供了足够的方法来访问文本