不确定之前是否已经回答过 - 我如何在两个关键字之间抓取字符串?
例如“故事”和“?”之间的字符串,
http://mywebsie.com/hello/blog/story/archieve/2012/5/?page=1
http://mywebsie.com/blog/story/archieve/2012/4/?page=1
http://mywebsie.com/blog/story/archieve/2012/?page=4
我只想要,
story/archieve/2012/5/
story/archieve/2012/4/
story/archieve/2012/
修改
如果我使用parse_url
,
$string = parse_url('http://mywebsie.com/blog/story/archieve/2012/4/?page=1');
echo $string_uri['path'];
我明白了,
/blog/story/archieve/2012/4/
但我不想包含'博客/ '
答案 0 :(得分:2)
另一个非常简单的方法是我们可以创建一个可以随时调用的简单函数。
<?php
// Create the Function to get the string
function GetStringBetween ($string, $start, $finish) {
$string = " ".$string;
$position = strpos($string, $start);
if ($position == 0) return "";
$position += strlen($start);
$length = strpos($string, $finish, $position) - $position;
return substr($string, $position, $length);
}
?>
以下是您的问题的示例用法
$string1="http://mywebsie.com/hello/blog/story/archieve/2012/5/?page=1";
$string2="http://mywebsie.com/blog/story/archieve/2012/4/?page=1";
$string3="http://mywebsie.com/blog/story/archieve/2012/?page=4";
echo GetStringBetween ($string1, "/blog/", "?page");
//result : story/archieve/2012/5/
echo GetStringBetween ($string2, "/blog/", "?page");
//result : story/archieve/2012/4/
echo GetStringBetween ($string3, "/blog/", "?page");
//result : story/archieve/2012/
有关详情,请参阅 http://codetutorial.com/howto/how-to-get-of-everything-string-between-two-tag-or-two-strings。
答案 1 :(得分:1)
使用parse_url()
。
http://php.net/manual/en/function.parse-url.php
$parts = parse_url('http://mywebsie.com/story/archieve/2012/4/?page=1');
echo $parts['path'];
您可以使用explode()
或其他任何需要的内容。
答案 2 :(得分:0)
如果可以安全地假设您要查找的子字符串在输入字符串中只出现一次:
function getInBetween($string, $from, $to) {
$fromAt = strpos($string, $from);
$fromTo = strpos($string, $to);
// if the upper limit is found before the lower
if($fromTo < $fromAt) return false;
// if the lower limit is not found, include everything from 0th
// you may modify this to just return false
if($fromAt === false) $fromAt = 0;
// if the upper limit is not found, include everything up to the end of string
if($fromTo === false) $fromTo = strlen($string);
return substr($string, $fromAt, $fromTo - $fromAt);
}
echo getInBetween("http://mywebsie.com/hello/blog/story/archieve/2012/5/?page=1", "story", '?'); // story/archieve/2012/5/