John
John

Reputation: 57

Is there a PHP function to pull out the string between two characters?

Is there a PHP function that grabs the string in between two characters. For example, I want to know what is between the percent and dollar symbol:

%HERE$

What is the function for this?

Upvotes: 2

Views: 300

Answers (2)

Gumbo
Gumbo

Reputation: 655159

You can use a regular expression to get that:

preg_match('/%([^$]*)\\$/', $str, $match)

If a match was found, $match[0] will contain the whole match and $match[1] the text between % and $.

But you can also use basic string functions like strpos and search for the % and the first $ after that:

if (($start = strpos($str, '%')) !== false && ($end = strpos($str, '$', $start)) !== false) {
    $match = substr($str, $start, $end-$start);
}

Upvotes: 3

Pascal MARTIN
Pascal MARTIN

Reputation: 400922

You could do that with a regex :

$string = 'test%HERE$glop';

$m = array();
if (preg_match('/%(.*?)\$/', $string, $m)) {
  var_dump($m[1]);
}

Will get you :

string 'HERE' (length=4)


Couple of notes :

  • The $ in the pattern has the be escaped, as it has a special meaning (end of string)
  • You want to match everything : .*
    • that's between % and $
    • But in non-gready mode : .*?
  • And you want that captured -- hence the () arround it.

Upvotes: 7

Related Questions