Php 如何删除句子的第一个单词并用另一个替换?
我有多个段落是动态循环的。我只想在检查段落的第一个单词是否包含我要查找的关键字后,为这些段落添加前缀 我试了很多次,但都没能得到一个完美的答案Php 如何删除句子的第一个单词并用另一个替换?,php,arrays,regex,string,replace,Php,Arrays,Regex,String,Replace,我有多个段落是动态循环的。我只想在检查段落的第一个单词是否包含我要查找的关键字后,为这些段落添加前缀 我试了很多次,但都没能得到一个完美的答案 $var="Hello, this paragraph is a series of related sentences developing a central idea, called the topic. Try to think idea."; if (stripos($var, 'hello,') !== false) { echo 'true
$var="Hello, this paragraph is a series of related sentences developing a central idea, called the topic. Try to think idea.";
if (stripos($var, 'hello,') !== false) {
echo 'true';
}
请帮忙。我收到了许多类似的、相关的答案,但我没有得到预期的答案。我希望使它与大小写不敏感的工作 我不能100%确定你的问题是否理解正确,但也许你可以试试这个
$var = "Hello, this paragraph is a series of related sentences developing a central idea, called the topic. Try to think idea.";
if (stripos($var, 'hello,') === 0) {
// this checks if the searched word is exactly at the beginning of the string
$var = 'YOUR PREFIX -- ' . $var;
}
echo $var;
如果要替换第一个单词,则应使用该代码
$var = "Hello, this paragraph is a series of related sentences developing a central idea, called the topic. Try to think idea.";
if (stripos($var, 'hello,') === 0) {
// this checks if the searched word is exactly at the beginning of the string
$var = preg_replace('/hello\,/i', 'REPLACE WITH', $var, 1);
}
echo $var;
您可以使用
strpos
if(strpos($var, 'Hello,') === 0 || strpos($var, 'hello,') === 0){
//Your Logic
}
问题可能是您正在查找的是
你好。
末尾有一个
,您正在搜索的文本在你好,
的末尾有一个,
。谢谢@NigelRen。。但问题是用另一个词替换hello。将(stripos($var,'hello')!==false)替换为(stripos($var,'hello')!==0)