Php 在strpos()搜索后打印字符串值

Php 在strpos()搜索后打印字符串值,php,Php,我对PHP还比较陌生,但我正在尝试编写一个脚本,在找到一两个特定单词后,只打印字符串中接下来的35个左右的字符。我熟悉使用strpos()查找特定值,只是不确定在找到我要设置的字符串值后如何打印接下来的35个字符 因此,如果输入的随机字符串包含“something”一词,该词来自最初输入的句子,“My friend have find in the park in the bench.”它只会打印“in the park in the bench.”这应该可以满足您的需要: substr($st

我对PHP还比较陌生,但我正在尝试编写一个脚本,在找到一两个特定单词后,只打印字符串中接下来的35个左右的字符。我熟悉使用
strpos()
查找特定值,只是不确定在找到我要设置的字符串值后如何打印接下来的35个字符


因此,如果输入的随机字符串包含“something”一词,该词来自最初输入的句子,“My friend have find in the park in the bench.”它只会打印“in the park in the bench.”这应该可以满足您的需要:

substr($string, strpos($string, $searchedWord) + strlen($searchedWord), 35);
您需要的是:


您正在搜索的单词的位置由您提到的
strpos()
决定;接下来,您需要跳过该单词并返回接下来的35个字符:

$str = 'My friend had found something in the park next to the bench.';
$needle = 'something';

substr($str, strpos($str, $needle) + strlen($needle), 35);
如果字符串中可能找不到
$needle
(在这种情况下
strpos()
返回
false
),则需要添加一个条件:

if (($pos = strpos($str, $needle)) !== false) {
    return substr($str, $pos + strlen($needle), 35);
} else {
    return ''; // search failed, return what you like
}
这假定在函数内部运行

另见:

if (($pos = strpos($str, $needle)) !== false) {
    return substr($str, $pos + strlen($needle), 35);
} else {
    return ''; // search failed, return what you like
}