PHP首次出现索引前后的字符串

时间:2012-04-11 17:01:52

标签: php string

我有一个字符串ex。 abcd.something.dcba我有一个索引前。 9(在这种情况下是e),我必须得到两个.之间的字符串。我不知道第一个点离索引有多远,也不知道第二个点有多远。那么有什么简单的方法在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

3 个答案:

答案 0 :(得分: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;

请注意,在索引之前/之后没有符号的情况下,您至少需要添加一些健全性检查。

答案 1 :(得分: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;

答案 2 :(得分: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;
    }
}