2012-09-11 34 views
0

我是一名初學者,並且遇到了使用RegExr工具發現的正則表達式的問題。使用正則表達式匹配PHP中的字符串

我從名爲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> 

這裏的,如果有哪個解析XML,然後檢查PHP代碼火柴;不幸的是它沒有顯示。

<?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; 
} 
?> 

我已經覈對過RegExr工具的正則表達式,它似乎很動聽 - 這裏有一個擷取畫面

enter image description here

回答

1

你在你與[^]正則表達式錯誤。插入符號用於否定方括號中的匹配字符。例如[^a]將不匹配a。

你的正則表達式並不理想。如果你想匹配的是「出售」的字符串我只是用後

/出售無堅不摧 - ([^ <] +)/

+0

謝謝,但它也不起作用 - 根據需要選擇整個字符串,而不是按照「For Sale - 」字符串出現的內容。這裏是RegExr的屏幕截圖 - http://i.imgur.com/ygszr.png –

+0

忘記RegExr中的內容或不匹配 - PHP只會爲您提供捕獲組(即括號)時所要求的內容。正如@ Maks3w指出,你可能需要訪問節點的'text()'而不是節點本身。 –

-1

您可以使用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"; 
} 
+0

問題是,舊的代碼沒有訪問XML元素的文本() – Maks3w

+0

謝謝,但我試過運行這個,但echo $ result仍然返回一堆0不幸的。 –

+0

我更新了你的正則表達式現在應該可以工作 – Maks3w

-1

你可以試試這個

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

foreach ($xml->channel->item as $item){ 
    preg_match("/For Sale(.*)<\/title>/siU", $item); 
    echo trim($item[1]," -"); 
} 
?> 
+0

你不需要處理結束標記,SimpleXML爲你提供了足夠的方法來訪問文本 – Maks3w