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 func开发者_Go百科tion for this?
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 :
.*?
- that's between
- And you want that captured -- hence the
()
arround it.
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);
}
精彩评论