0

我正在尝试解析一个字符串,但返回的内容不正确,我试图从 doc=? 中提取问号?和幻灯片=?,但相反我得到

文档编号: &doc=9729&slide=214679&#doc=9729&slide=21

幻灯片 ID: &slide=214679&#doc=9729

细绳 :

http://securefinder.com/ajax_query/delimiter.aspx?q=LNG&f=1.1&doc=9729&slide=214679&#doc=9729&slide=214679&

似乎它不接受 & 作为分隔符。

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



    ?>
4

2 回答 2

1

考虑使用prase_url()分解 url,然后parse_str()在查询结果上使用,首先分解查询,然后分解#结果,&最后分解结果=

这样您就不需要编写自己的解析逻辑。从这里你会得到一个很好的数组来操作而不是试图弄清楚如何操作你的字符串。

于 2012-12-27T20:29:22.310 回答
0

尝试,使用preg_match

$str = "http:/securefinder.com/ajax_query/delimiter.aspx?q=LNG&f=1.1&doc=9729&slide=214679&#doc=9729&slide=214679&";

preg_match("/doc=(.*?)&/i", $str, $d);    
preg_match("/slide=(.*?)&/i", $str, $s);

$doc_id   =  $d[1];
$slide_id =  $s[1];

echo 'doc id:' . $doc_id ;
echo 'slide id:'. $slide_id;
于 2012-12-27T20:31:15.353 回答