function from_to($str, $from, $to) {
return substr(
$str,
strpos($str, $from),
strpos($str, $to) - strpos($str, $from) + strlen($to)
);
}
这是基本的字符串操作。请多阅读手册。
关闭所有边缘情况的更强大的解决方案(并包括文档):
<?php
/**
* @param string $string The string to match against
* @param string $from Starting substring, from here
* @param string $to Ending substring, to here
*
* @return string Substring containing all the letters from $from to $to inclusive.
* @throws Exception In case of $to being found before $from
*/
function from_to($string, $from, $to) {
//Calculate where each substring is found inside of $string
$pos_from = strpos($string, $from);
$pos_to = strpos($string, $to);
//The function will break if $to appears before $from, throw an exception.
if ($pos_from > $pos_to) {
throw new Exception("'$from' ($pos_from) appears before '$to' ($pos_to)");
}
return substr(
$string,
$pos_from, //From where the $from starts (first character of $from)
$pos_to - $pos_from + strlen($to) //To where the $to ends. (last character of $to)
);
}
$str = "hello world, and this not foo is mars";
try {
echo from_to($str, 'world', 'hell');
}
catch (Exception $e) {
//In case 'hell' appeared before 'world'
echo from_to($str, 'hell', 'world');
}