1

不确定之前是否已经回答过这个问题 - 如何在两个关键字之间获取字符串?

例如 ' story ' 和 a '之间的字符串',

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/

但我不想包括“博客/

4

3 回答 3

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

于 2014-12-16T23:28:40.553 回答
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()或任何您需要的东西。

于 2012-04-12T01:02:00.793 回答
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/
于 2012-04-12T01:44:06.887 回答