[英]Strpos() returning unexpected string
I for the life of me cannot figure out why this is not working. 我为我的生活无法弄清楚为什么这不起作用。
$value="http://www.google.com/trends/hottrends/atom/feed?pn=p1";
$startvar="http://";
$endvar="/";
$start = strpos($value,$startvar);
$end = strpos($value,$endvar,$start) + 8;
$results = substr($value,$start,$end-$start);
echo $results;
No matter what I do it will always return the http:// which I do not want. 无论我做什么,它总会返回我不想要的http://。 I just want the www.google.com. 我只想要www.google.com。 I'm using this in another area and there it's behaving exactly like I want. 我在另一个区域使用它,它的行为与我想要的完全一样。 I did get this to work if I use a numerical starting point and not $startvar but that won't necessarily work all the time. 如果我使用数字起点而不是$ startvar,我确实可以使用它,但这不一定会一直有效。
I'm sure it's something simple that I'm missing. 我确信这很简单,我很想念。
Thanks Bruce 谢谢布鲁斯
You need to skip over the whole $startvar
token to get to the next bit of your string. 您需要跳过整个$startvar
标记才能到达字符串的下一位。 strpos
returns the beginning of the match. strpos
返回匹配的开头。
$start = strpos($value,$startvar) + strlen($startvar);
Although you will also need to make sure that strpos
hasn't returned false
, which it will do if $startvar
is not found: 虽然你还需要确保strpos
没有返回false
,如果找不到$startvar
它将会这样做:
$pos = strpos($value, $startvar)
if ($pos !== false)
{
$start = $pos + strlen($startvar)
//... other steps here...
}
If your objective is simply to parse a URL, you can use the PHP function parse_url , which will make your life much easier. 如果您的目标只是解析URL,则可以使用PHP函数parse_url ,这将使您的生活更轻松。
Why not use 为什么不用
$value="http://www.google.com/trends/hottrends/atom/feed?pn=p1";
list($a,$b,$c) = split('[/]',$value);
echo'<br/>a = ',$a;
echo'<br/>b = ',$b;
echo'<br/>c = ',$c;
You will find that $c
is your answer. 你会发现$c
是你的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.