2011-06-11 256 views
0

我正在访问mysql数据库并显示一列。在此列是一个很长的字符串可以说其是:如何在字符串中使用php查找字符串

<image identifier="540aa2ad-9a8d-454d-b915-605b884e76d5"> 
    <file><![CDATA[images/[email protected]@._V1._SY317_CR0,0,214,317_.jpg]]></file> 
    <title/> 
    <link/> 

一切深藏<![CDATA[images/.jpg]]></file>之间会改变每一行,我想任何呼应位于它们之间的代码段。

有人帮忙吗?

感谢

编辑

到目前为止,我有:

function inStr ($needle, $haystack) 
{ 
    $needlechars = strlen($needle); //gets the number of characters in our needle 
    $i = 0; 
    for($i=0; $i < strlen($haystack); $i++) //creates a loop for the number of characters in our haystack 
    { 
    if(substr($haystack, $i, $needlechars) == $needle) //checks to see if the needle is in this segment of the haystack 
    { 
     return TRUE; //if it is return true 
    } 
    } 
    return FALSE; //if not, return false 
} 
$img = ' 
SELECT * 
FROM `item` 
'; 
$result0 = mysql_query($img); 

while ($row0 = mysql_fetch_array($result0)){ 

$haystack = $row0['elements']; 
$needle = '<![CDATA[images/'; 
} 

if(inStr($needle, $haystack)) 
{ 
    echo "string is present"; 
} 
+0

'preg_match()'。 – 2011-06-11 17:10:55

+0

如果你想要搜索的东西是一致的,那么带strpos的substr可能会更好。 – ldg 2011-06-11 17:13:19

+0

请你举个例子,我曾经使用过strpos。 – reece 2011-06-11 17:14:26

回答

1
$cdata_part = preg_quote('<![CDATA[images/'); 
$end_part = preg_quote('.jpg]]></file>'); 

if (preg_match("#{$cdata_part}(.+?){$end_part}#", $text, $matches)) { 
    echo $matches[1]; 
} 
0

如果你有XML,那么很容易:

<?php 
$xml = <<<END 
<image identifier="540aa2ad-9a8d-454d-b915-605b884e76d5"> 
    <file><![CDATA[images/[email protected]@._V1._SY317_CR0,0,214,317_.jpg]]></file> 
    <title/> 
    <link/> 
</image> 
END; 

$file = (string) simplexml_load_string($xml)->file; 

echo $file; 

您可能需要调整如果你使用simplexml“路径”向我们提供了部分文本块。你听起来像XML中有几个图像,但因为我不知道它形成了,我不能告诉你如何迭代它。

哦,这也会返回.jpg部分,但是如果您知道它是.jpg,删除扩展就像substr($file, 0, -4)一样简单。