考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,写语句的正确方法是if ($a contains 'are')
什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,写语句的正确方法是if ($a contains 'are')
什么?
现在使用 PHP 8,您可以使用str_contains执行此操作:
if (str_contains('How are you', 'are')) {
echo 'true';
}
PHP 8 之前
您可以使用strpos()
用于查找一个字符串在另一个字符串中出现的函数:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
请注意,使用!== false
是故意的(既!= false
不会也=== true
不会返回所需的结果);strpos()
返回针字符串在 haystack 字符串中开始的偏移量,false
如果未找到针,则返回布尔值。由于 0 是有效的偏移量,而 0 是“错误的”,我们不能使用更简单的结构,例如!strpos($a, 'are')
.
strpos
正如其他用户所提到的,您可以使用正则表达式,因为与 相比,它更适合单词匹配。strpos
检查 for也将are
返回 true,例如:fare、care、stare 等。这些意外匹配可以通过使用单词边界在正则表达式中简单地避免。
一个简单的匹配are
可能看起来像这样:
$a = 'How are you?';
if (preg_match('/\bare\b/', $a)) {
echo 'true';
}
在性能方面,strpos
大约快三倍。当我一次进行 100 万次比较时,需要preg_match
1.5 秒才能完成,因为strpos
它需要 0.5 秒。
编辑:为了搜索字符串的任何部分,而不仅仅是逐字搜索,我建议使用正则表达式,如
$a = 'How are you?';
$search = 'are y';
if(preg_match("/{$search}/i", $a)) {
echo 'true';
}
正i
则表达式末尾的 将正则表达式更改为不区分大小写,如果您不想这样做,可以将其省略。
现在,在某些情况下,这可能会很成问题,因为 $search 字符串没有以任何方式进行清理,我的意思是,在某些情况下它可能无法通过检查,就好像$search
用户输入他们可以添加一些可能表现得像的字符串一些不同的正则表达式...
此外,这是一个很好的工具,用于测试和查看各种正则表达式Regex101的解释
要将两组功能组合成一个多功能功能(包括可选择区分大小写),您可以使用以下内容:
function FindString($needle,$haystack,$i,$word)
{ // $i should be "" or "i" for case insensitive
if (strtoupper($word)=="W")
{ // if $word is "W" then word search instead of string in string search.
if (preg_match("/\b{$needle}\b/{$i}", $haystack))
{
return true;
}
}
else
{
if(preg_match("/{$needle}/{$i}", $haystack))
{
return true;
}
}
return false;
// Put quotes around true and false above to return them as strings instead of as bools/ints.
}
要记住的另一件事是,它\b
不适用于英语以外的其他语言。
\b
表示单词的开头或结尾(Word Boundary)。此正则表达式将匹配苹果派中的苹果,但不会匹配菠萝、苹果车或烤苹果中的苹果。“咖啡馆”怎么说?我们如何在正则表达式中提取“café”这个词?实际上, \bcafé\b 行不通。为什么?因为“café”包含非ASCII字符:é。\b 不能简单地与 Unicode 一起使用,例如 समुद्र、감사、месяц 和 .
当你想提取 Unicode 字符时,你应该直接定义代表单词边界的字符。
答案:
(?<=[\s,.:;"']|^)UNICODE_WORD(?=[\s,.:;"']|$)
所以为了在 PHP 中使用答案,你可以使用这个函数:
function contains($str, array $arr) {
// Works in Hebrew and any other unicode characters
// Thanks https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
// Thanks https://www.phpliveregex.com/
if (preg_match('/(?<=[\s,.:;"\']|^)' . $word . '(?=[\s,.:;"\']|$)/', $str)) return true;
}
如果你想搜索单词数组,你可以使用这个:
function arrayContainsWord($str, array $arr)
{
foreach ($arr as $word) {
// Works in Hebrew and any other unicode characters
// Thanks https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
// Thanks https://www.phpliveregex.com/
if (preg_match('/(?<=[\s,.:;"\']|^)' . $word . '(?=[\s,.:;"\']|$)/', $str)) return true;
}
return false;
}
从 PHP 8.0.0 开始,您现在可以使用str_contains
<?php
if (str_contains('abc', '')) {
echo "Checking the existence of the empty string will always
return true";
}
这是一个小实用函数,在这种情况下很有用
// returns true if $needle is a substring of $haystack
function contains($needle, $haystack)
{
return strpos($haystack, $needle) !== false;
}
要确定一个字符串是否包含另一个字符串,您可以使用 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,如果您进行的==
比较不起作用,则需要执行===
符号是一种==
比较,测试左边的变量/表达式/常量是否与右边的变量/表达式/常量具有相同的值。
符号是一个===
比较,看两个变量/表达式/常量是否相等AND
具有相同的类型 - 即两者都是字符串或两者都是整数。
虽然这些答案中的大多数会告诉您字符串中是否出现子字符串,但如果您正在寻找特定的word而不是substring ,这通常不是您想要的。
有什么不同?子字符串可以出现在其他词中:
缓解这种情况的一种方法是使用正则表达式和单词边界( \b
):
function containsWord($str, $word)
{
return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i', $str);
}
这种方法没有上面提到的相同的误报,但它确实有一些自己的边缘情况。单词边界匹配非单词字符 ( \W
),这将是任何不是a-z
、A-Z
、0-9
或_
. 这意味着数字和下划线将被视为单词字符,这样的场景将失败:
如果您想要比这更准确的东西,您将不得不开始进行英语语法解析,这是一个相当大的蠕虫罐(并且假设正确使用语法,无论如何,这并不总是给定的)。
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply, == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'.";
}
else {
echo "The string '$findme' was found in the string '$mystring',";
echo " and exists at position $pos.";
}
?>
对 SamGoody 和 Lego Stormtroopr 的评论。
如果您正在寻找一种 PHP 算法来根据多个单词的接近度/相关性对搜索结果进行排名,这里有一种仅使用 PHP 生成搜索结果的快速简便的方法:
其他布尔搜索方法的问题,例如strpos()
, preg_match()
,strstr()
或stristr()
基于向量空间模型和tf-idf(词频-逆文档频率)的PHP方法:
这听起来很困难,但出乎意料地容易。
如果我们想在一个字符串中搜索多个单词,核心问题是我们如何为每个单词分配一个权重?
如果我们可以根据它们在整个字符串中的代表性来对字符串中的术语进行加权,我们可以按照与查询最匹配的结果对结果进行排序。
这就是向量空间模型的思路,与SQL 全文搜索的工作原理相差不远:
function get_corpus_index($corpus = array(), $separator=' ') {
$dictionary = array();
$doc_count = array();
foreach($corpus as $doc_id => $doc) {
$terms = explode($separator, $doc);
$doc_count[$doc_id] = count($terms);
// tf–idf, short for term frequency–inverse document frequency,
// according to wikipedia is a numerical statistic that is intended to reflect
// how important a word is to a document in a corpus
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('document_frequency' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$doc_id])) {
$dictionary[$term]['document_frequency']++;
$dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0);
}
$dictionary[$term]['postings'][$doc_id]['term_frequency']++;
}
//from http://phpir.com/simple-search-the-vector-space-model/
}
return array('doc_count' => $doc_count, 'dictionary' => $dictionary);
}
function get_similar_documents($query='', $corpus=array(), $separator=' '){
$similar_documents=array();
if($query!=''&&!empty($corpus)){
$words=explode($separator,$query);
$corpus=get_corpus_index($corpus, $separator);
$doc_count=count($corpus['doc_count']);
foreach($words as $word) {
if(isset($corpus['dictionary'][$word])){
$entry = $corpus['dictionary'][$word];
foreach($entry['postings'] as $doc_id => $posting) {
//get term frequency–inverse document frequency
$score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2);
if(isset($similar_documents[$doc_id])){
$similar_documents[$doc_id]+=$score;
}
else{
$similar_documents[$doc_id]=$score;
}
}
}
}
// length normalise
foreach($similar_documents as $doc_id => $score) {
$similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id];
}
// sort from high to low
arsort($similar_documents);
}
return $similar_documents;
}
情况1
$query = 'are';
$corpus = array(
1 => 'How are you?',
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
结果
Array
(
[1] => 0.52832083357372
)
案例二
$query = 'are';
$corpus = array(
1 => 'how are you today?',
2 => 'how do you do',
3 => 'here you are! how are you? Are we done yet?'
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
结果
Array
(
[1] => 0.54248125036058
[3] => 0.21699250014423
)
案例 3
$query = 'we are done';
$corpus = array(
1 => 'how are you today?',
2 => 'how do you do',
3 => 'here you are! how are you? Are we done yet?'
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
结果
Array
(
[3] => 0.6813781191217
[1] => 0.54248125036058
)
有很多改进要做,但该模型提供了一种从自然查询中获得良好结果的方法,这些查询没有布尔运算符,例如strpos()
、或。preg_match()
strstr()
stristr()
诺塔贝尼
可选地在搜索单词之前消除冗余
从而减少索引大小并减少存储需求
更少的磁盘 I/O
更快的索引和因此更快的搜索。
1.归一化
2. 停用词消除
3.字典替换
用具有相同或相似含义的其他单词替换单词。(例如:用“饥饿”替换“饥饿”和“饥饿”的实例)
可以执行进一步的算法措施(雪球)以进一步减少单词的基本含义。
用对应的十六进制替换颜色名称
通过降低精度来减少数值是标准化文本的其他方法。
资源
使用不区分大小写的匹配stripos()
:
if (stripos($string,$stringToSearch) !== false) {
echo 'true';
}
如果你想避免“假”和“真”的问题,可以使用 substr_count:
if (substr_count($a, 'are') > 0) {
echo "at least one 'are' is present!";
}
它比 strpos 慢一点,但它避免了比较问题。
if (preg_match('/(are)/', $a)) {
echo 'true';
}
我有点印象深刻的是,这里使用的答案strpos
和strstr
类似的函数都没有提到多字节字符串函数(2015-05-08)。
基本上,如果您在查找包含某些特定语言字符(例如德语、法语、葡萄牙语、西班牙语等)的单词时遇到问题(例如: ä、é、ô、ç、º、ñ),您可能需要先于的函数mb_
。因此,接受的答案将使用mb_strpos
or mb_stripos
(对于不区分大小写的匹配):
if (mb_strpos($a,'are') !== false) {
echo 'true';
}
如果您不能保证所有数据都是 UTF-8 的 100%,您可能需要使用这些mb_
函数。
一篇很好的文章可以理解为什么每个软件开发人员都绝对、肯定地必须了解 Unicode 和字符集(没有借口!),作者是Joel Spolsky。
在 PHP 中,验证字符串是否包含某个子字符串的最佳方法是使用一个简单的辅助函数,如下所示:
function contains($haystack, $needle, $caseSensitive = false) {
return $caseSensitive ?
(strpos($haystack, $needle) === FALSE ? FALSE : TRUE):
(stripos($haystack, $needle) === FALSE ? FALSE : TRUE);
}
strpos
查找字符串中第一次出现区分大小写的子字符串的位置。stripos
查找不区分大小写的子字符串在字符串中第一次出现的位置。myFunction($haystack, $needle) === FALSE ? FALSE : TRUE
确保myFunction
当子字符串的索引为 0 时始终返回布尔值并修复意外行为。$caseSensitive ? A : B
根据 的值选择strpos
或来完成工作。stripos
$caseSensitive
var_dump(contains('bare','are')); // Outputs: bool(true)
var_dump(contains('stare', 'are')); // Outputs: bool(true)
var_dump(contains('stare', 'Are')); // Outputs: bool(true)
var_dump(contains('stare', 'Are', true)); // Outputs: bool(false)
var_dump(contains('hair', 'are')); // Outputs: bool(false)
var_dump(contains('aren\'t', 'are')); // Outputs: bool(true)
var_dump(contains('Aren\'t', 'are')); // Outputs: bool(true)
var_dump(contains('Aren\'t', 'are', true)); // Outputs: bool(false)
var_dump(contains('aren\'t', 'Are')); // Outputs: bool(true)
var_dump(contains('aren\'t', 'Are', true)); // Outputs: bool(false)
var_dump(contains('broad', 'are')); // Outputs: bool(false)
var_dump(contains('border', 'are')); // Outputs: bool(false)
您可以使用以下strstr
功能:
$haystack = "I know programming";
$needle = "know";
$flag = strstr($haystack, $needle);
if ($flag){
echo "true";
}
不使用内置函数:
$haystack = "hello world";
$needle = "llo";
$i = $j = 0;
while (isset($needle[$i])) {
while (isset($haystack[$j]) && ($needle[$i] != $haystack[$j])) {
$j++;
$i = 0;
}
if (!isset($haystack[$j])) {
break;
}
$i++;
$j++;
}
if (!isset($needle[$i])) {
echo "YES";
}
else{
echo "NO ";
}
下面的函数也可以工作,并且不依赖于任何其他函数;它只使用原生 PHP 字符串操作。就个人而言,我不推荐这样做,但你可以看看它是如何工作的:
<?php
if (!function_exists('is_str_contain')) {
function is_str_contain($string, $keyword)
{
if (empty($string) || empty($keyword)) return false;
$keyword_first_char = $keyword[0];
$keyword_length = strlen($keyword);
$string_length = strlen($string);
// case 1
if ($string_length < $keyword_length) return false;
// case 2
if ($string_length == $keyword_length) {
if ($string == $keyword) return true;
else return false;
}
// case 3
if ($keyword_length == 1) {
for ($i = 0; $i < $string_length; $i++) {
// Check if keyword's first char == string's first char
if ($keyword_first_char == $string[$i]) {
return true;
}
}
}
// case 4
if ($keyword_length > 1) {
for ($i = 0; $i < $string_length; $i++) {
/*
the remaining part of the string is equal or greater than the keyword
*/
if (($string_length + 1 - $i) >= $keyword_length) {
// Check if keyword's first char == string's first char
if ($keyword_first_char == $string[$i]) {
$match = 1;
for ($j = 1; $j < $keyword_length; $j++) {
if (($i + $j < $string_length) && $keyword[$j] == $string[$i + $j]) {
$match++;
}
else {
return false;
}
}
if ($match == $keyword_length) {
return true;
}
// end if first match found
}
// end if remaining part
}
else {
return false;
}
// end for loop
}
// end case4
}
return false;
}
}
测试:
var_dump(is_str_contain("test", "t")); //true
var_dump(is_str_contain("test", "")); //false
var_dump(is_str_contain("test", "test")); //true
var_dump(is_str_contain("test", "testa")); //flase
var_dump(is_str_contain("a----z", "a")); //true
var_dump(is_str_contain("a----z", "z")); //true
var_dump(is_str_contain("mystringss", "strings")); //true
substr_count
许多使用检查结果的答案是否为>0
. 但是由于该if
语句认为零与 false 相同,因此您可以避免该检查并直接编写:
if (substr_count($a, 'are')) {
要检查是否不存在,请添加!
运算符:
if (!substr_count($a, 'are')) {
我遇到了一些麻烦,最后我选择创建自己的解决方案。不使用正则表达式引擎:
function contains($text, $word)
{
$found = false;
$spaceArray = explode(' ', $text);
$nonBreakingSpaceArray = explode(chr(160), $text);
if (in_array($word, $spaceArray) ||
in_array($word, $nonBreakingSpaceArray)
) {
$found = true;
}
return $found;
}
您可能会注意到,以前的解决方案不是作为另一个词的前缀的答案。为了使用您的示例:
$a = 'How are you?';
$b = "a skirt that flares from the waist";
$c = "are";
对于上面的示例,两者都$a
包含$b
,$c
但您可能希望您的函数告诉您仅$a
包含$c
。
使用strstr()和stristr()从字符串中查找单词出现的另一种选择如下:
<?php
$a = 'How are you?';
if (strstr($a,'are')) // Case sensitive
echo 'true';
if (stristr($a,'are')) // Case insensitive
echo 'true';
?>
它可以通过三种不同的方式完成:
$a = 'How are you?';
1-stristr()
if (strlen(stristr($a,"are"))>0) {
echo "true"; // are Found
}
2- strpos()
if (strpos($a, "are") !== false) {
echo "true"; // are Found
}
3- preg_match()
if( preg_match("are",$a) === 1) {
echo "true"; // are Found
}
简写版本
$result = false!==strpos($a, 'are');
Do not use preg_match()
if you only want to check if one string is contained in another string. Use strpos()
or strstr()
instead as they will be faster. (http://in2.php.net/preg_match)
if (strpos($text, 'string_name') !== false){
echo 'get the string';
}
为了找到一个“单词”,而不是出现实际上可能是另一个单词的一部分的一系列字母,以下将是一个很好的解决方案。
$string = 'How are you?';
$array = explode(" ", $string);
if (in_array('are', $array) ) {
echo 'Found the word';
}
您应该使用不区分大小写的格式,因此如果输入的值在small
或caps
无关紧要。
<?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 中找到针。
也许你可以使用这样的东西:
<?php
findWord('Test all OK');
function findWord($text) {
if (strstr($text, 'ok')) {
echo 'Found a word';
}
else
{
echo 'Did not find a word';
}
}
?>
如果要检查字符串是否包含多个特定单词,可以执行以下操作:
$badWords = array("dette", "capitale", "rembourser", "ivoire", "mandat");
$string = "a string with the word ivoire";
$matchFound = preg_match_all("/\b(" . implode($badWords,"|") . ")\b/i", $string, $matches);
if ($matchFound) {
echo "a bad word has been found";
}
else {
echo "your string is okay";
}
例如,这对于在发送电子邮件时避免垃圾邮件很有用。
strpos 函数可以正常工作,但是如果您想case-insensitive
检查段落中的单词,则可以stripos
使用PHP
.
例如,
$result = stripos("I love PHP, I love PHP too!", "php");
if ($result === false) {
// Word does not exist
}
else {
// Word exists
}
查找字符串中第一次出现不区分大小写的子字符串的位置。
如果字符串中不存在该单词,则它将返回 false 否则它将返回该单词的位置。
可以使用以下函数检查字符串:
function either_String_existor_not($str, $character) {
return strpos($str, $character) !== false;
}
您需要使用相同/不相同的运算符,因为 strpos 可以返回 0 作为它的索引值。如果您喜欢三元运算符,请考虑使用以下内容(我承认似乎有点倒退):
echo FALSE === strpos($a,'are') ? 'false': 'true';
检查字符串是否包含特定单词?
这意味着必须将字符串解析为单词(参见下面的注释)。
执行此操作并指定分隔符的一种方法是使用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 的字符表控制,并且如果发生特定于语言环境的匹配可能会有所不同 (..)
利用:
$text = 'This is a test';
echo substr_count($text, 'is'); // 2
// So if you want to check if is exists in the text just put
// in a condition like this:
if (substr_count($text, 'is') > 0) {
echo "is exists";
}
特定字符串的另一种解决方案:
$subject = 'How are you?';
$pattern = '/are/';
preg_match($pattern, $subject, $match);
if ($match[0] == 'are') {
echo true;
}
你也可以使用strpos()
函数。
您还可以对多字节字符串strchr()
和. 这些函数返回部分字符串,如果没有找到。strrchr()
mb_strchr()
mb_strrchr()
FALSE
strchr()
- 查找第一次出现的字符串(是 的别名strstr()
)。strrchr()
- 查找字符串中最后一次出现的字符。我认为一个好主意是使用mb_stpos
:
$haystack = 'How are you?';
$needle = 'are';
if (mb_strpos($haystack, $needle) !== false) {
echo 'true';
}
因为此解决方案对所有 Unicode 字符都区分大小写且安全。
但你也可以这样做(还没有响应):
if (count(explode($needle, $haystack)) > 1) {
echo 'true';
}
此解决方案对 Unicode 字符也区分大小写且安全。
此外,您不要在表达式中使用否定,这增加了代码的可读性。
这是使用函数的其他解决方案:
function isContainsStr($haystack, $needle) {
return count(explode($needle, $haystack)) > 1;
}
if (isContainsStr($haystack, $needle)) {
echo 'true';
}
一个更简单的选择:
return ( ! empty($a) && strpos($a, 'are'))? true : false;
利用:
$a = 'How are you?';
if (mb_strpos($a, 'are')) {
echo 'true';
}
它执行多字节安全 strpos() 操作。