Run
Run

Reputation: 57176

How to grab string between two keywords in PHP

Not sure if this has been answered before - how can I grab string between two keywords?

For instance the string between a 'story' and 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

I just want,

story/archieve/2012/5/
story/archieve/2012/4/
story/archieve/2012/

EDIT:

If I use parse_url,

$string = parse_url('http://mywebsie.com/blog/story/archieve/2012/4/?page=1');
echo $string_uri['path'];

I get,

/blog/story/archieve/2012/4/

but I don't want to include 'blog/'

Upvotes: 1

Views: 167

Answers (3)

MichaelCalvin
MichaelCalvin

Reputation: 163

Another very simple way is we can create a simple function that can be invoked at any time.

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

and here's an example usage for your question

$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/

For more detail please read http://codetutorial.com/howto/how-to-get-of-everything-string-between-two-tag-or-two-strings.

Upvotes: 2

Andreas Wong
Andreas Wong

Reputation: 60516

If it is safe to assume that the substrings you are looking for occur exactly once in the input string:

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/

Upvotes: 0

Brad
Brad

Reputation: 163301

Use 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'];

You can use explode() or whatever you need from there.

Upvotes: 1

Related Questions