I am trying to parse a string but what I get returned is incorrect , I am trying to extract just the question mark from doc=? and slide=?, but instead I get
doc id:&doc=9729&slide=214679&#doc=9729&slide=21
slide id:&slide=214679&#doc=9729
string :
http:/securefinder.com/ajax_query/delimiter.aspx?q=LNG&f=1.1&doc=9729&slide=214679&#doc=9729&slide=214679&
It seems it does not accept & as the delimiting character.
<?php
function from_to($string, $from, $to) {
//Calculate where each substring is found inside of $string
$pos_from = strpos($string, $from);
$pos_to = strpos($string, $to);
//The function will break if $to appears before $from, throw an exception.
if ($pos_from > $pos_to) {
}
return substr(
$string,
$pos_from, //From where the $from starts (first character of $from)
$pos_to - $pos_from + strlen($to) //To where the $to ends. (last character of $to)
);
}
$str = "http:/securefinder.com/ajax_query/delimiter.aspx?q=LNG&f=1.1&doc=9729&slide=214679&#doc=9729&slide=214679&";
$doc_id = from_to($str, 'doc=', '&');
$slide_id = from_to($str, 'slide=', '&');
echo 'doc id:' . $doc_id ;
echo 'slide id:'. $slide_id;
?>
Consider using
prase_url()to break up the url and then useparse_str()on the query result to first break up your query by#, the results of that by&, and finally the results of that by=.This way you don’t need to write your own parsing logic. From this you will get a nice array to manipulate instead of trying to figure out how to manipulate your string.