我的字符串具有以下模式。 Some text on some more text before some text
。
我如何找到
答案 0 :(得分:3)
正则表达式对此有些过分。只需从你找到“之前”的地方做一个子串:
$str = 'Some text on some more text before some text';
// Find " on "
$start = strpos($str, " on ");
// Check for errors
// Note the 3 ='s
if($start === FALSE) {
// Error occurred, do something
}
$start += 4; // Go after "on"
// Find " before "
$end = strpos($str, " before ", $start);
// Check for errors
// Note the 3 ='s
if($end === FALSE) {
// Error occurred, do something
}
// Get just the part we want
$length = $end - $start;
$result = substr($str, $start, $end - $start);
答案 1 :(得分:2)
preg_match('~\bon\b(.+)\bbefore\b~',$text,$match);
//use $match[1]; e.g $text=$match[1];
答案 2 :(得分:1)
考虑使用正则表达式:
$text= "Some text on some more text before some text";
$pattern = '/^.* on(.*)before.*$/';
preg_match($pattern, $text, $matches);
if($matches) {
print $matches[1];
}
答案 3 :(得分:1)
试试这个:
<?php
$string = 'Some text on some more text before some text';
$newString = preg_replace('/(.*)on(.*)before(.*)/', '$2', $string);
echo $newString;
正则表达式:http://regexr.com?2uqq7
答案 4 :(得分:1)
$var="Some text on some more text before some text";
preg_match('/\bon\b(.*)\bbefore\b/',$var,$match);
//Edit: You can use `(.+)` too if, by any chance, there is no text between 'on' and 'before'.
print_r ($match);
//$match[1] has "some more text"
这是你想要的吗?
至于位置事物,你可以echo strrpos($var, " on ");
如果我正确地得到这个(正如你在评论中说的那样“on”周围有空格。echo strrpos($var, "before");
这将会返回第一个角色的位置。
答案 5 :(得分:-5)
$str = 'Some text on some more text before some text';
$str = str_replace(array('on','before'), '', $str);