0

我有一个字符串前。abcd.something.dcba我有一个索引前。9 (在这种情况下是e),我必须得到两个.s 之间的字符串。我不知道第一个点离索引有多远,也不知道第二个点有多远。那么有没有简单的方法在php中做到这一点?字符串 ex 中还有很多.s。a.b.c.d.something.d.c.b.a

其他几个例子:

bef.ore.something.af.t.er指数:12 =something

bef.ore.something.af.t.er指数:5 =ore

bef.ore.something.af.t.er指数:19 =af

4

3 回答 3

3

作为起点,您可以尝试:

$input = 'a.b.something.c.def';
$index = 9;
$delimiter = '.';

/*
 * get length of input string
 */
$len = strlen($input);

/*
 * find the index of the first delimiter *after* the index
 */
$afterIdx = strpos($input, $delimiter, $index);

/*
 * find the index of the last delimiter *before* the index 
 * figure out how many characters are left after the index and negate that - 
 * this makes the function ignore that many characters from the end of the string,
 * effectively inspecting only the part of the string up to the index
 * and add +1 to that because we are interested in the location of the first symbol after that
 */
$beforeIdx = strrpos($input, $delimiter, -($len - $index)) + 1; 

/*
 * grab the part of the string beginning at the last delimiter 
 * and spanning up to the next delimiter
 */
$sub = substr($input, $beforeIdx, $afterIdx - $beforeIdx);
echo $sub;

请注意,对于索引之前/之后没有符号的情况,您至少需要添加一些完整性检查。

于 2012-04-11T17:17:30.123 回答
1

在这种情况下,正则表达式将是您的朋友:

$regex = '/\.?([\w]+)/';
$string = 'a.b.c.d.something.d.c.b.a';
preg_match_all($regex, $string, $result);
print_r($result[1]);

注意:如果您要查找特定单词,只需将 [\w]+ 替换为您要查找的单词。

@ 19greg96 我知道你现在想要什么,'DCoder 示例的另一种但类似的方法是:

$string = 'a.b.something.d.c.b.a';
$index = 9;
$delimiter = '.';

$last_index = strpos($string, $delimiter, $index);
$substr = substr($string, 0, $last_index);
$substr = substr($substr, strrpos($substr, $delimiter) + 1);
echo $substr;
于 2012-04-11T17:08:23.600 回答
0

将字符串分解成一个数组并通过 foreach() 传递:

$str='a.b.c.d.something.d.c.b.a';
$parts=explode('.',$str);
foreach($parts as $part) {
    if($part=='something') {
        echo('Found it!');
        break;
    }
}
于 2012-04-11T17:09:27.773 回答