[英]how to find a string within a string using php
我正在訪問 mysql 數據庫並顯示一列。 在此列中是一個長字符串,可以這樣說:
<image identifier="540aa2ad-9a8d-454d-b915-605b884e76d5">
<file><![CDATA[images/MV5BMTg5OTMxNzk4Nl5BMl5BanBnXkFtZTcwOTk1MjAwNQ@@._V1._SY317_CR0,0,214,317_.jpg]]></file>
<title/>
<link/>
<![CDATA[images/
and .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";
}
$cdata_part = preg_quote('<![CDATA[images/');
$end_part = preg_quote('.jpg]]></file>');
if (preg_match("#{$cdata_part}(.+?){$end_part}#", $text, $matches)) {
echo $matches[1];
}
如果你有 XML,那么很簡單:
<?php
$xml = <<<END
<image identifier="540aa2ad-9a8d-454d-b915-605b884e76d5">
<file><![CDATA[images/MV5BMTg5OTMxNzk4Nl5BMl5BanBnXkFtZTcwOTk1MjAwNQ@@._V1._SY317_CR0,0,214,317_.jpg]]></file>
<title/>
<link/>
</image>
END;
$file = (string) simplexml_load_string($xml)->file;
echo $file;
如果您只向我們提供了部分文本 blob,您可能需要稍微調整 simplexml“路徑”。 您聽起來好像 XML 中有幾個圖像,但是由於我不知道它已形成,因此我無法真正告訴您如何對其進行迭代。
哦,這也將返回 .jpg 部分,但是如果您知道它是.jpg,則刪除擴展名就像substr($file, 0, -4)
一樣簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.