考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
当前回答
短手版本
$result = false!==strpos($a, 'are');
其他回答
您应该使用不区分大小写的格式,因此如果输入的值是小写或大写,则无所谓。
<?php
$grass = "This is pratik joshi";
$needle = "pratik";
if (stripos($grass,$needle) !== false) {
/*If i EXCLUDE : !== false then if string is found at 0th location,
still it will say STRING NOT FOUND as it will return '0' and it
will goto else and will say NOT Found though it is found at 0th location.*/
echo 'Contains word';
}else{
echo "does NOT contain word";
}
?>
在这里,stripos在不考虑箱子(小/帽)的情况下,在heystack中找到了针头。
带输出的PHPCode样本
strpos函数工作得很好,但是如果您想对段落中的单词进行不区分大小写的检查,那么可以使用PHP的stripos函数。
例如
$result = stripos("I love PHP, I love PHP too!", "php");
if ($result === false) {
// Word does not exist
}
else {
// Word exists
}
查找字符串中不区分大小写的子字符串第一次出现的位置。
如果字符串中不存在该单词,则返回false,否则返回单词的位置。
检查字符串是否包含特定单词?
这意味着字符串必须解析为单词(请参见下面的注释)。
执行此操作并指定分隔符的一种方法是使用preg_split(doc):
<?php
function contains_word($str, $word) {
// split string into words
// separators are substrings of at least one non-word character
$arr = preg_split('/\W+/', $str, NULL, PREG_SPLIT_NO_EMPTY);
// now the words can be examined each
foreach ($arr as $value) {
if ($value === $word) {
return true;
}
}
return false;
}
function test($str, $word) {
if (contains_word($str, $word)) {
echo "string '" . $str . "' contains word '" . $word . "'\n";
} else {
echo "string '" . $str . "' does not contain word '" . $word . "'\n" ;
}
}
$a = 'How are you?';
test($a, 'are');
test($a, 'ar');
test($a, 'hare');
?>
跑一次就可以
$ php -f test.php
string 'How are you?' contains word 'are'
string 'How are you?' does not contain word 'ar'
string 'How are you?' does not contain word 'hare'
注意:这里我们不是指每个符号序列的单词。
单词的实际定义是PCRE正则表达式引擎,其中单词是仅由单词字符组成的子字符串,由非单词字符分隔。
“单词”字符是任何字母、数字或下划线字符,也就是说,可以是Perl“单词”一部分的任何字符。这个字母和数字的定义由PCRE的字符控制表,如果正在进行特定于区域设置的匹配,则可能会有所不同(..)
我有点印象深刻,这里没有一个使用strpos、strstr和类似函数的答案提到多字节字符串函数(2015-05-08)。
基本上,如果您在查找某些语言(如德语、法语、葡萄牙语、西班牙语等)特定字符的单词时遇到困难(例如:ä,é,ô,ç,º,ñ),您可能需要在函数前面加上mb_。因此,接受的答案将使用mb_strpos或mb_stripos(用于不区分大小写的匹配):
if (mb_strpos($a,'are') !== false) {
echo 'true';
}
如果不能保证所有数据都是100%的UTF-8格式,则可能需要使用mb_函数。
乔尔·斯波尔斯基(Joel Spolsky)的一篇很好的文章解释了为什么每个软件开发人员都必须了解Unicode和字符集(没有借口!)。
要确定一个字符串是否包含另一个字符串,可以使用PHP函数strpos()。
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )`
<?php
$haystack = 'how are you';
$needle = 'are';
if (strpos($haystack,$needle) !== false) {
echo "$haystack contains $needle";
}
?>
警告:
如果您正在搜索的针位于干草堆的开始位置,它将返回位置0,如果您进行==比较,但这不起作用,则需要执行===
A==符号是一个比较,用于测试左侧的变量/表达式/常量是否与右侧的变量/表达/常量具有相同的值。
A==符号是比较两个变量/表达式/常量是否相等并且具有相同的类型,即两者都是字符串或两者都是整数。
使用这种方法的优点之一是,与str_contains()不同,每个PHP版本都支持此函数。