how to find a string within a string using php
I am accessing a mysql database and displaying a column. in this column is a long string lets say its this:
<image identifier="540aa2ad-9a8d-454d-b915-605b884e76d5">
<file><![CDATA[images/MV5BMTg5OTMxNzk4Nl5BMl5BanBnXkFtZTcwOTk1MjAwNQ@@._V1._SY317_CR0,0,214,317_.jpg]]></file>
<title/>
<link/>
whatever lies between <![CDATA[images/
and .jpg]]></file>
will开发者_如何学Python change on every row and i want to echo whatever lies between them pieces of code.
anyone help?
thanks
edit
so far i have:
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];
}
If you have XML, then it's easy:
<?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;
You may need to adjust the simplexml "path" a bit if you only supplied us with a partial text blob. You make it sound like there are several images within the XML, but as I don't know it's formed I cannot really tell you how to iterate over it.
Oh, and this will return the .jpg portion too, but removing an extension is as simple as substr($file, 0, -4)
if you know it is .jpg.
精彩评论