Consider:
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are')
?
假设我有上面的代码,如果($a包含'是'),那么写语句的正确方法是什么?
40 个解决方案
#1
5154
You can use the strpos()
function which is used to find the occurrence of one string inside another one:
您可以使用strpos()函数来查找在另一个字符串中出现的字符串:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
Note that the use of !== false
is deliberate; strpos()
returns either the offset at which the needle string begins in the haystack string, or the boolean false
if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are')
.
注意,使用!== false是故意的;strpos()返回的是在haystack字符串中开始的指针字符串的偏移量,或者如果没有找到指针的布尔false。因为0是一个有效的偏移量,0是“falsey”,我们不能使用更简单的结构,比如strpos($a, 'are')。
#2
417
You could use regular expressions, it's better for word matching compared to strpos as mentioned by other users it will also return true for strings such as fare, care, stare etc. This can simply be avoided in the regular expression by using word boundaries.
您可以使用正则表达式,与其他用户所提到的strpos相比,它更适合于文字匹配,它也会返回true,如fare、care、stare等。这可以通过使用单词边界在正则表达式中避免。
A simple match for are could look something like this:
一个简单的匹配是这样的:
$a = 'How are you?';
if (preg_match('/\bare\b/',$a))
echo 'true';
On the performance side, strpos is about three times faster and have in mind, when I did one million compares at once, it took preg match 1.5 seconds to finish and for strpos it took 0.5 seconds.
在性能方面,strpos的速度要快3倍,而且在我做了100万次的对比之后,它花了1.5秒的时间来完成preg的匹配,而strpos则花了0.5秒。
#4
183
Here is a little utility function that is useful in situations like this
这里有一个小实用函数在这种情况下是有用的。
// returns true if $needle is a substring of $haystack
function contains($needle, $haystack)
{
return strpos($haystack, $needle) !== false;
}
#5
108
While most of these answers will tell you if a substring appears in your string, that's usually not what you want if you're looking for a particular word, and not a substring.
虽然大多数这些答案会告诉你一个子字符串是否出现在你的字符串中,但如果你在寻找一个特定的单词,而不是一个子字符串,那通常不是你想要的。
What's the difference? Substrings can appear within other words:
有什么区别呢?子字符串可以出现在其他单词中:
- The "are" at the beginning of "area"
- 在“区域”开头的“are”
- The "are" at the end of "hare"
- "are"在"hare"后面
- The "are" in the middle of "fares"
- "are"在"票价"中间
One way to mitigate this would be to use a regular expression coupled with word boundaries (\b
):
缓解这一问题的一种方法是使用正则表达式加上单词边界(\b):
function containsWord($str, $word)
{
return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i', $str);
}
This method doesn't have the same false positives noted above, but it does have some edge cases of its own. Word boundaries match on non-word characters (\W
), which are going to be anything that isn't a-z
, A-Z
, 0-9
, or _
. That means digits and underscores are going to be counted as word characters and scenarios like this will fail:
这个方法没有上面提到的假阳性,但它确实有自己的一些边缘情况。单词边界匹配非单词字符(\W),这将是任何不是a-z, a-z, 0-9,或_。这意味着数字和下划线将被计算为单词字符,这样的场景会失败:
- The "are" in "What _are_ you thinking?"
- “你在想什么?”
- The "are" in "lol u dunno wut those are4?"
- 在“lol u dunno wut,这些是4吗?”
If you want anything more accurate than this, you'll have to start doing English language syntax parsing, and that's a pretty big can of worms (and assumes proper use of syntax, anyway, which isn't always a given).
如果您想要比这更准确的东西,您将不得不开始进行英语语法分析,这是一种相当大的蠕虫(并且假定语法的正确使用,无论如何,这并不总是一个给定的)。
#6
87
To determine whether a string contains another string you can use the PHP function strpos().
要确定一个字符串是否包含另一个字符串,可以使用PHP函数strpos()。
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
int strpos(字符串$haystack,混合$needle [, int $offset = 0])
<?php
$haystack = 'how are you';
$needle = 'are';
if (strpos($haystack,$needle) !== false) {
echo '$haystack contains $needle';
}
?>
CAUTION:
警告:
If the needle you are searching for is at the beginning of the haystack it will return position 0, if you do a ==
compare that will not work, you will need to do a ===
如果你搜索的指针在haystack的开头,它会返回位置0,如果你做了一个==比较,那么你需要做一个===。
A ==
sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right.
A ==符号是一个比较,测试变量/表达式/常量是否与右边的变量/表达式/常量有相同的值。
A ===
sign is a comparison to see whether two variables / expresions / constants are equal AND
have the same type - i.e. both are strings or both are integers.
A ==符号是一个比较,看看两个变量/ expresions /常量是否相等,是否具有相同的类型,即两者都是字符串,或者两者都是整数。
#7
#8
53
看大小写敏感():
<?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.";
}
?>
#9
35
If you want to avoid the "falsey" and "truthy" problem, you can use substr_count:
如果您想避免“falsey”和“truthy”问题,可以使用substr_count:
if (substr_count($a, 'are') > 0) {
echo "at least one 'are' is present!";
}
It's a bit slower than strpos but it avoids the comparison problems.
它比strpos慢一点,但它避免了比较问题。
#10
35
Make use of case-insensitve matching using stripos()
:
使用stripos()来使用不敏感匹配:
if (stripos($string,$stringToSearch) !== false) {
echo 'true';
}
#11
29
Peer to SamGoody and Lego Stormtroopr comments.
Peer to SamGoody和Lego Stormtroopr评论。
If you are looking for a PHP algorithm to rank search results based on proximity/relevance of multiple words here comes a quick and easy way of generating search results with PHP only:
如果你正在寻找一种PHP算法来根据多个单词的邻近性/相关性对搜索结果进行排序,这里有一个简单快捷的方法,可以用PHP生成搜索结果:
Issues with the other boolean search methods such as strpos()
, preg_match()
, strstr()
or stristr()
其他布尔搜索方法的问题,如strpos()、preg_match()、strstr()或stristr()
- can't search for multiple words
- 不能搜索多个单词?
- results are unranked
- 结果优先排序
PHP method based on Vector Space Model and tf-idf (term frequency–inverse document frequency):
基于向量空间模型和tf-idf(术语频率逆文档频率)的PHP方法:
It sounds difficult but is surprisingly easy.
这听起来很困难,但却出奇的容易。
If we want to search for multiple words in a string the core problem is how we assign a weight to each one of them?
如果我们想要在字符串中搜索多个单词,核心问题是我们如何为每个单词分配权重?
If we could weight the terms in a string based on how representative they are of the string as a whole, we could order our results by the ones that best match the query.
如果我们可以根据字符串作为一个整体的代表性来对字符串进行加权,我们可以通过最匹配查询的结果来排序结果。
This is the idea of the vector space model, not far from how SQL full-text search works:
这就是向量空间模型的概念,与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;
}
CASE 1
案例1
$query = 'are';
$corpus = array(
1 => 'How are you?',
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULT
结果
Array
(
[1] => 0.52832083357372
)
CASE 2
案例2
$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>';
RESULTS
结果
Array
(
[1] => 0.54248125036058
[3] => 0.21699250014423
)
CASE 3
案例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>';
RESULTS
结果
Array
(
[3] => 0.6813781191217
[1] => 0.54248125036058
)
There are plenty of improvements to be made but the model provides a way of getting good results from natural queries, which don't have boolean operators such as strpos()
, preg_match()
, strstr()
or stristr()
.
虽然有很多改进,但是模型提供了一种从自然查询中获得好的结果的方法,这些查询没有布尔运算符,如strpos()、preg_match()、strstr()或stristr()。
NOTA BENE
留心
Optionally eliminating redundancy prior to search the words
在搜索单词之前可以选择消除冗余。
-
thereby reducing index size and resulting in less storage requirement
从而减少了索引的大小,从而减少了存储需求。
-
less disk I/O
磁盘I / O更少
-
faster indexing and a consequently faster search.
更快的索引和更快的搜索。
1. Normalisation
1。正常化
- Convert all text to lower case
- 将所有文本转换为小写。
2. Stopword elimination
2。Stopword消除
- Eliminate words from the text which carry no real meaning (like 'and', 'or', 'the', 'for', etc.)
- 从没有真正意义的文本中删除单词(比如“and”、“or”、“the”、“for”等)。
3. Dictionary substitution
3所示。字典替换
-
Replace words with others which have an identical or similar meaning. (ex:replace instances of 'hungrily' and 'hungry' with 'hunger')
将单词替换为具有相同或相似含义的单词。(ex:用“饥饿”代替“饥饿”和“饥饿”)
-
Further algorithmic measures (snowball) may be performed to further reduce words to their essential meaning.
进一步的算法措施(雪球)可以进一步减少单词的基本含义。
-
The replacement of colour names with their hexadecimal equivalents
用十六进制等价物替换颜色名称。
-
The reduction of numeric values by reducing precision are other ways of normalising the text.
通过减少精度来减少数值是实现文本规范化的其他方法。
RESOURCES
资源
- http://linuxgazette.net/164/sephton.html
- http://linuxgazette.net/164/sephton.html
- http://snowball.tartarus.org/
- http://snowball.tartarus.org/
- MySQL Fulltext Search Score Explained
- MySQL全文搜索分数说明。
- http://dev.mysql.com/doc/internals/en/full-text-search.html
- http://dev.mysql.com/doc/internals/en/full-text-search.html
- http://en.wikipedia.org/wiki/Vector_space_model
- http://en.wikipedia.org/wiki/Vector_space_model
- http://en.wikipedia.org/wiki/Tf%E2%80%93idf
- http://en.wikipedia.org/wiki/Tf%E2%80%93idf
- http://phpir.com/simple-search-the-vector-space-model/
- http://phpir.com/simple-search-the-vector-space-model/
#12
28
Another option is to use the strstr() function. Something like:
另一种选择是使用strstr()函数。喜欢的东西:
if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}
Point to note: The strstr() function is case-sensitive. For a case-insensitive search, use the stristr() function.
注意:strstr()函数是大小写敏感的。对于不区分大小写的搜索,使用stristr()函数。
#13
25
I'm a bit impressed that none of the answers here that used strpos
, strstr
and similar functions mentioned Multibyte String Functions yet (2015-05-08).
我对使用strpos、strstr和类似功能的所有答案都没有提到多字节字符串函数(2015-05-08)有一点印象深刻。
Basically, if you're having trouble finding words with characters specific to some languages, such as German, French, Portuguese, Spanish, etc. (e.g.: ä, é, ô, ç, º, ñ), you may want to precede the functions with mb_
. Therefore, the accepted answer would use mb_strpos
or mb_stripos
(for case-insensitive matching) instead:
基本上,如果你找不到的话人物特定的一些语言,如德语,法语,葡萄牙语,西班牙语,等等。(例如:a、e、o、c,º,n),您可能想要先于mb_的功能。因此,接受的答案将使用mb_strpos或mb_stripos(不区分大小写的匹配):
if (mb_strpos($a,'are') !== false) {
echo 'true';
}
If you cannot guarantee that all your data is 100% in UTF-8, you may want to use the mb_
functions.
如果您不能保证所有数据都是100%的UTF-8,那么您可能希望使用mb_函数。
A good article to understand why is The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky.
一篇好的文章要理解为什么每个软件开发人员绝对要绝对的最小,肯定要知道Joel Spolsky的Unicode和字符集(没有借口!)
#14
21
The function below also works and does not depend on any other function; it uses only native PHP string manipulation. Personally, I do not recommend this, but you can see how it works:
下面的函数也可以工作,不依赖于任何其他函数;它只使用本机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;
}
}
Test:
测试:
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
#15
21
if (preg_match('are', $a)) {
echo 'true';
}
#16
19
I had some trouble with this, and finally I chose to create my own solution. Without using regular expression engine:
我在这方面遇到了一些麻烦,最后我选择了创建自己的解决方案。不使用正则表达式引擎:
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;
}
You may notice that the previous solutions are not an answer for the word being used as a prefix for another. In order to use your example:
您可能会注意到,前面的解决方案并不是作为另一个前缀的前缀。为了使用你的例子:
$a = 'How are you?';
$b = "a skirt that flares from the waist";
$c = "are";
With the samples above, both $a
and $b
contains $c
, but you may want your function to tell you that only $a
contains $c
.
在上面的示例中,$a和$b都包含$c,但是您可能希望您的函数告诉您只有$a包含$c。
#17
17
You can use the strstr
function:
可以使用strstr函数:
$haystack = "I know programming";
$needle = "know";
$flag = strstr($haystack, $needle);
if ($flag){
echo "true";
}
Without using an inbuilt function:
不使用内置函数:
$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 ";
}
#18
16
In PHP, the best way to verify if a string contains a certain substring, is to use a simple helper function like this:
在PHP中,验证字符串是否包含某个子字符串的最好方法是使用如下的简单助手函数:
function contains($haystack, $needle, $caseSensitive = false) {
return $caseSensitive ?
(strpos($haystack, $needle) === FALSE ? FALSE : TRUE):
(stripos($haystack, $needle) === FALSE ? FALSE : TRUE);
}
Explanation:
-
strpos
finds the position of the first occurrence of a case-sensitive substring in a string. - strpos找到一个字符串中第一次出现大小写敏感子字符串的位置。
-
stripos
finds the position of the first occurrence of a case-insensitive substring in a string. - stripos查找一个字符串中第一次出现不区分大小写的子字符串的位置。
-
myFunction($haystack, $needle) === FALSE ? FALSE : TRUE
ensures thatmyFunction
always returns a boolean and fixes unexpected behavior when the index of the substring is 0. - myFunction($haystack, $needle) == FALSE ?FALSE: TRUE确保myFunction总是返回一个布尔值,并在子字符串的索引为0时修复意外的行为。
-
$caseSensitive ? A : B
selects eitherstrpos
orstripos
to do the work, depending on the value of$caseSensitive
. - caseSensitive美元?A: B选择了strpos或stripos来做这项工作,这取决于你的钱的价值。
Output:
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)
#19
14
The short-hand version
速记版本
$result = false!==strpos($a, 'are');
#20
13
You should use case Insensitive format,so if the entered value is in small
or caps
it wont matter.
您应该使用大小写不敏感的格式,因此,如果输入的值是小的或大写的,它就不重要了。
<?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";
}
?>
Here stripos finds needle in heystack without considering case (small/caps).
在这里,stripos在heystack发现了针,而不考虑病例(小的/大写的)。
PHPCode样本与输出
#21
13
In order to find a 'word', rather than the occurrence of a series of letters that could in fact be a part of another word, the following would be a good solution.
为了找到一个“单词”,而不是一系列字母的出现,而这些字母实际上可能是另一个单词的一部分,下面的单词将是一个很好的解决方案。
$string = 'How are you?';
$array = explode(" ", $string);
if (in_array('are', $array) ) {
echo 'Found the word';
}
#22
#23
12
It can be done in three different ways:
可以用三种不同的方式来完成:
$a = 'How are you?';
1- stristr()
1 - stristr()
if (strlen(stristr($a,"are"))>0) {
echo "true"; // are Found
}
2- strpos()
2 -()大小写敏感
if (strpos($a, "are") !== false) {
echo "true"; // are Found
}
3- preg_match()
3 - preg_match()
if( preg_match("are",$a) === 1) {
echo "true"; // are Found
}
#24
12
Maybe you could use something like this:
也许你可以用这样的方法:
<?php
findWord('Test all OK');
function findWord($text) {
if (strstr($text, 'ok')) {
echo 'Found a word';
}
else
{
echo 'Did not find a word';
}
}
?>
#25
10
$a = 'how are you';
if (strpos($a,'are')) {
echo 'true';
}
#26
10
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)
如果您只想检查一个字符串是否包含在另一个字符串中,请不要使用preg_match()。使用strpos()或strstr()代替,因为它们将更快。(http://in2.php.net/preg_match)
if (strpos($text, 'string_name') !== false){
echo 'get the string';
}
#27
9
You need to use identical/not identical operators because strpos can return 0 as it's index value. If you like ternary operators, consider using the following (seems a little backwards I'll admit):
您需要使用相同/不同的操作符,因为strpos可以返回0作为它的索引值。如果你喜欢三元运算符,可以考虑使用下面的方法(我承认这有点落后):
echo FALSE === strpos($a,'are') ? 'false': 'true';
#28
9
If you want to check if the string contains several specifics words, you can do:
如果您想检查字符串是否包含几个具体的单词,您可以这样做:
$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";
}
This is useful to avoid spam when sending emails for example.
这对于在发送电子邮件时避免垃圾邮件是有用的。
#29
8
The strpos function works fine, but if you want to do case-insensitive
checking for a word in a paragraph then you can make use of the stripos
function of PHP
.
strpos函数可以正常工作,但是如果您想在段落中对一个单词进行不区分大小写的检查,那么您可以使用PHP的stripos函数。
For example,
例如,
$result = stripos("I love PHP, I love PHP too!", "php");
if ($result === false) {
// Word does not exist
}
else {
// Word exists
}
Find the position of the first occurrence of a case-insensitive substring in a string.
查找字符串中第一次出现不区分大小写的子字符串的位置。
If the word doesn't exist in the string then it will return false else it will return the position of the word.
如果字符串中不存在单词,那么它将返回false,否则它将返回单词的位置。
#30
8
Lot of answers that use substr_count
checks if the result is >0
. But since the if
statement considers zero the same as false, you can avoid that check and write directly:
大量的答案使用substr_count检查结果是否为>0。但由于if语句认为0与false相同,可以避免直接进行检查和写入:
if (substr_count($a, 'are')) {
To check if not present, add the !
operator:
要检查是否不存在,请添加!接线员:
if (!substr_count($a, 'are')) {
#1
5154
You can use the strpos()
function which is used to find the occurrence of one string inside another one:
您可以使用strpos()函数来查找在另一个字符串中出现的字符串:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
Note that the use of !== false
is deliberate; strpos()
returns either the offset at which the needle string begins in the haystack string, or the boolean false
if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are')
.
注意,使用!== false是故意的;strpos()返回的是在haystack字符串中开始的指针字符串的偏移量,或者如果没有找到指针的布尔false。因为0是一个有效的偏移量,0是“falsey”,我们不能使用更简单的结构,比如strpos($a, 'are')。
#2
417
You could use regular expressions, it's better for word matching compared to strpos as mentioned by other users it will also return true for strings such as fare, care, stare etc. This can simply be avoided in the regular expression by using word boundaries.
您可以使用正则表达式,与其他用户所提到的strpos相比,它更适合于文字匹配,它也会返回true,如fare、care、stare等。这可以通过使用单词边界在正则表达式中避免。
A simple match for are could look something like this:
一个简单的匹配是这样的:
$a = 'How are you?';
if (preg_match('/\bare\b/',$a))
echo 'true';
On the performance side, strpos is about three times faster and have in mind, when I did one million compares at once, it took preg match 1.5 seconds to finish and for strpos it took 0.5 seconds.
在性能方面,strpos的速度要快3倍,而且在我做了100万次的对比之后,它花了1.5秒的时间来完成preg的匹配,而strpos则花了0.5秒。
#3
#4
183
Here is a little utility function that is useful in situations like this
这里有一个小实用函数在这种情况下是有用的。
// returns true if $needle is a substring of $haystack
function contains($needle, $haystack)
{
return strpos($haystack, $needle) !== false;
}
#5
108
While most of these answers will tell you if a substring appears in your string, that's usually not what you want if you're looking for a particular word, and not a substring.
虽然大多数这些答案会告诉你一个子字符串是否出现在你的字符串中,但如果你在寻找一个特定的单词,而不是一个子字符串,那通常不是你想要的。
What's the difference? Substrings can appear within other words:
有什么区别呢?子字符串可以出现在其他单词中:
- The "are" at the beginning of "area"
- 在“区域”开头的“are”
- The "are" at the end of "hare"
- "are"在"hare"后面
- The "are" in the middle of "fares"
- "are"在"票价"中间
One way to mitigate this would be to use a regular expression coupled with word boundaries (\b
):
缓解这一问题的一种方法是使用正则表达式加上单词边界(\b):
function containsWord($str, $word)
{
return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i', $str);
}
This method doesn't have the same false positives noted above, but it does have some edge cases of its own. Word boundaries match on non-word characters (\W
), which are going to be anything that isn't a-z
, A-Z
, 0-9
, or _
. That means digits and underscores are going to be counted as word characters and scenarios like this will fail:
这个方法没有上面提到的假阳性,但它确实有自己的一些边缘情况。单词边界匹配非单词字符(\W),这将是任何不是a-z, a-z, 0-9,或_。这意味着数字和下划线将被计算为单词字符,这样的场景会失败:
- The "are" in "What _are_ you thinking?"
- “你在想什么?”
- The "are" in "lol u dunno wut those are4?"
- 在“lol u dunno wut,这些是4吗?”
If you want anything more accurate than this, you'll have to start doing English language syntax parsing, and that's a pretty big can of worms (and assumes proper use of syntax, anyway, which isn't always a given).
如果您想要比这更准确的东西,您将不得不开始进行英语语法分析,这是一种相当大的蠕虫(并且假定语法的正确使用,无论如何,这并不总是一个给定的)。
#6
87
To determine whether a string contains another string you can use the PHP function strpos().
要确定一个字符串是否包含另一个字符串,可以使用PHP函数strpos()。
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
int strpos(字符串$haystack,混合$needle [, int $offset = 0])
<?php
$haystack = 'how are you';
$needle = 'are';
if (strpos($haystack,$needle) !== false) {
echo '$haystack contains $needle';
}
?>
CAUTION:
警告:
If the needle you are searching for is at the beginning of the haystack it will return position 0, if you do a ==
compare that will not work, you will need to do a ===
如果你搜索的指针在haystack的开头,它会返回位置0,如果你做了一个==比较,那么你需要做一个===。
A ==
sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right.
A ==符号是一个比较,测试变量/表达式/常量是否与右边的变量/表达式/常量有相同的值。
A ===
sign is a comparison to see whether two variables / expresions / constants are equal AND
have the same type - i.e. both are strings or both are integers.
A ==符号是一个比较,看看两个变量/ expresions /常量是否相等,是否具有相同的类型,即两者都是字符串,或者两者都是整数。
#7
54
Using strstr()
or stristr()
if your search should be case insensitive would be another option.
使用strstr()或stristr()如果您的搜索不区分大小写,则是另一种选择。
#8
53
看大小写敏感():
<?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.";
}
?>
#9
35
If you want to avoid the "falsey" and "truthy" problem, you can use substr_count:
如果您想避免“falsey”和“truthy”问题,可以使用substr_count:
if (substr_count($a, 'are') > 0) {
echo "at least one 'are' is present!";
}
It's a bit slower than strpos but it avoids the comparison problems.
它比strpos慢一点,但它避免了比较问题。
#10
35
Make use of case-insensitve matching using stripos()
:
使用stripos()来使用不敏感匹配:
if (stripos($string,$stringToSearch) !== false) {
echo 'true';
}
#11
29
Peer to SamGoody and Lego Stormtroopr comments.
Peer to SamGoody和Lego Stormtroopr评论。
If you are looking for a PHP algorithm to rank search results based on proximity/relevance of multiple words here comes a quick and easy way of generating search results with PHP only:
如果你正在寻找一种PHP算法来根据多个单词的邻近性/相关性对搜索结果进行排序,这里有一个简单快捷的方法,可以用PHP生成搜索结果:
Issues with the other boolean search methods such as strpos()
, preg_match()
, strstr()
or stristr()
其他布尔搜索方法的问题,如strpos()、preg_match()、strstr()或stristr()
- can't search for multiple words
- 不能搜索多个单词?
- results are unranked
- 结果优先排序
PHP method based on Vector Space Model and tf-idf (term frequency–inverse document frequency):
基于向量空间模型和tf-idf(术语频率逆文档频率)的PHP方法:
It sounds difficult but is surprisingly easy.
这听起来很困难,但却出奇的容易。
If we want to search for multiple words in a string the core problem is how we assign a weight to each one of them?
如果我们想要在字符串中搜索多个单词,核心问题是我们如何为每个单词分配权重?
If we could weight the terms in a string based on how representative they are of the string as a whole, we could order our results by the ones that best match the query.
如果我们可以根据字符串作为一个整体的代表性来对字符串进行加权,我们可以通过最匹配查询的结果来排序结果。
This is the idea of the vector space model, not far from how SQL full-text search works:
这就是向量空间模型的概念,与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;
}
CASE 1
案例1
$query = 'are';
$corpus = array(
1 => 'How are you?',
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULT
结果
Array
(
[1] => 0.52832083357372
)
CASE 2
案例2
$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>';
RESULTS
结果
Array
(
[1] => 0.54248125036058
[3] => 0.21699250014423
)
CASE 3
案例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>';
RESULTS
结果
Array
(
[3] => 0.6813781191217
[1] => 0.54248125036058
)
There are plenty of improvements to be made but the model provides a way of getting good results from natural queries, which don't have boolean operators such as strpos()
, preg_match()
, strstr()
or stristr()
.
虽然有很多改进,但是模型提供了一种从自然查询中获得好的结果的方法,这些查询没有布尔运算符,如strpos()、preg_match()、strstr()或stristr()。
NOTA BENE
留心
Optionally eliminating redundancy prior to search the words
在搜索单词之前可以选择消除冗余。
-
thereby reducing index size and resulting in less storage requirement
从而减少了索引的大小,从而减少了存储需求。
-
less disk I/O
磁盘I / O更少
-
faster indexing and a consequently faster search.
更快的索引和更快的搜索。
1. Normalisation
1。正常化
- Convert all text to lower case
- 将所有文本转换为小写。
2. Stopword elimination
2。Stopword消除
- Eliminate words from the text which carry no real meaning (like 'and', 'or', 'the', 'for', etc.)
- 从没有真正意义的文本中删除单词(比如“and”、“or”、“the”、“for”等)。
3. Dictionary substitution
3所示。字典替换
-
Replace words with others which have an identical or similar meaning. (ex:replace instances of 'hungrily' and 'hungry' with 'hunger')
将单词替换为具有相同或相似含义的单词。(ex:用“饥饿”代替“饥饿”和“饥饿”)
-
Further algorithmic measures (snowball) may be performed to further reduce words to their essential meaning.
进一步的算法措施(雪球)可以进一步减少单词的基本含义。
-
The replacement of colour names with their hexadecimal equivalents
用十六进制等价物替换颜色名称。
-
The reduction of numeric values by reducing precision are other ways of normalising the text.
通过减少精度来减少数值是实现文本规范化的其他方法。
RESOURCES
资源
- http://linuxgazette.net/164/sephton.html
- http://linuxgazette.net/164/sephton.html
- http://snowball.tartarus.org/
- http://snowball.tartarus.org/
- MySQL Fulltext Search Score Explained
- MySQL全文搜索分数说明。
- http://dev.mysql.com/doc/internals/en/full-text-search.html
- http://dev.mysql.com/doc/internals/en/full-text-search.html
- http://en.wikipedia.org/wiki/Vector_space_model
- http://en.wikipedia.org/wiki/Vector_space_model
- http://en.wikipedia.org/wiki/Tf%E2%80%93idf
- http://en.wikipedia.org/wiki/Tf%E2%80%93idf
- http://phpir.com/simple-search-the-vector-space-model/
- http://phpir.com/simple-search-the-vector-space-model/
#12
28
Another option is to use the strstr() function. Something like:
另一种选择是使用strstr()函数。喜欢的东西:
if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}
Point to note: The strstr() function is case-sensitive. For a case-insensitive search, use the stristr() function.
注意:strstr()函数是大小写敏感的。对于不区分大小写的搜索,使用stristr()函数。
#13
25
I'm a bit impressed that none of the answers here that used strpos
, strstr
and similar functions mentioned Multibyte String Functions yet (2015-05-08).
我对使用strpos、strstr和类似功能的所有答案都没有提到多字节字符串函数(2015-05-08)有一点印象深刻。
Basically, if you're having trouble finding words with characters specific to some languages, such as German, French, Portuguese, Spanish, etc. (e.g.: ä, é, ô, ç, º, ñ), you may want to precede the functions with mb_
. Therefore, the accepted answer would use mb_strpos
or mb_stripos
(for case-insensitive matching) instead:
基本上,如果你找不到的话人物特定的一些语言,如德语,法语,葡萄牙语,西班牙语,等等。(例如:a、e、o、c,º,n),您可能想要先于mb_的功能。因此,接受的答案将使用mb_strpos或mb_stripos(不区分大小写的匹配):
if (mb_strpos($a,'are') !== false) {
echo 'true';
}
If you cannot guarantee that all your data is 100% in UTF-8, you may want to use the mb_
functions.
如果您不能保证所有数据都是100%的UTF-8,那么您可能希望使用mb_函数。
A good article to understand why is The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky.
一篇好的文章要理解为什么每个软件开发人员绝对要绝对的最小,肯定要知道Joel Spolsky的Unicode和字符集(没有借口!)
#14
21
The function below also works and does not depend on any other function; it uses only native PHP string manipulation. Personally, I do not recommend this, but you can see how it works:
下面的函数也可以工作,不依赖于任何其他函数;它只使用本机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;
}
}
Test:
测试:
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
#15
21
if (preg_match('are', $a)) {
echo 'true';
}
#16
19
I had some trouble with this, and finally I chose to create my own solution. Without using regular expression engine:
我在这方面遇到了一些麻烦,最后我选择了创建自己的解决方案。不使用正则表达式引擎:
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;
}
You may notice that the previous solutions are not an answer for the word being used as a prefix for another. In order to use your example:
您可能会注意到,前面的解决方案并不是作为另一个前缀的前缀。为了使用你的例子:
$a = 'How are you?';
$b = "a skirt that flares from the waist";
$c = "are";
With the samples above, both $a
and $b
contains $c
, but you may want your function to tell you that only $a
contains $c
.
在上面的示例中,$a和$b都包含$c,但是您可能希望您的函数告诉您只有$a包含$c。
#17
17
You can use the strstr
function:
可以使用strstr函数:
$haystack = "I know programming";
$needle = "know";
$flag = strstr($haystack, $needle);
if ($flag){
echo "true";
}
Without using an inbuilt function:
不使用内置函数:
$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 ";
}
#18
16
In PHP, the best way to verify if a string contains a certain substring, is to use a simple helper function like this:
在PHP中,验证字符串是否包含某个子字符串的最好方法是使用如下的简单助手函数:
function contains($haystack, $needle, $caseSensitive = false) {
return $caseSensitive ?
(strpos($haystack, $needle) === FALSE ? FALSE : TRUE):
(stripos($haystack, $needle) === FALSE ? FALSE : TRUE);
}
Explanation:
-
strpos
finds the position of the first occurrence of a case-sensitive substring in a string. - strpos找到一个字符串中第一次出现大小写敏感子字符串的位置。
-
stripos
finds the position of the first occurrence of a case-insensitive substring in a string. - stripos查找一个字符串中第一次出现不区分大小写的子字符串的位置。
-
myFunction($haystack, $needle) === FALSE ? FALSE : TRUE
ensures thatmyFunction
always returns a boolean and fixes unexpected behavior when the index of the substring is 0. - myFunction($haystack, $needle) == FALSE ?FALSE: TRUE确保myFunction总是返回一个布尔值,并在子字符串的索引为0时修复意外的行为。
-
$caseSensitive ? A : B
selects eitherstrpos
orstripos
to do the work, depending on the value of$caseSensitive
. - caseSensitive美元?A: B选择了strpos或stripos来做这项工作,这取决于你的钱的价值。
Output:
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)
#19
14
The short-hand version
速记版本
$result = false!==strpos($a, 'are');
#20
13
You should use case Insensitive format,so if the entered value is in small
or caps
it wont matter.
您应该使用大小写不敏感的格式,因此,如果输入的值是小的或大写的,它就不重要了。
<?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";
}
?>
Here stripos finds needle in heystack without considering case (small/caps).
在这里,stripos在heystack发现了针,而不考虑病例(小的/大写的)。
PHPCode样本与输出
#21
13
In order to find a 'word', rather than the occurrence of a series of letters that could in fact be a part of another word, the following would be a good solution.
为了找到一个“单词”,而不是一系列字母的出现,而这些字母实际上可能是另一个单词的一部分,下面的单词将是一个很好的解决方案。
$string = 'How are you?';
$array = explode(" ", $string);
if (in_array('are', $array) ) {
echo 'Found the word';
}
#22
13
Another option to finding the occurrence of a word from a string using strstr() and stristr() is like the following:
使用strstr()和stristr()从字符串中查找单词的出现的另一种方法是:
<?php
$a = 'How are you?';
if (strstr($a,'are')) // Case sensitive
echo 'true';
if (stristr($a,'are')) // Case insensitive
echo 'true';
?>
#23
12
It can be done in three different ways:
可以用三种不同的方式来完成:
$a = 'How are you?';
1- stristr()
1 - stristr()
if (strlen(stristr($a,"are"))>0) {
echo "true"; // are Found
}
2- strpos()
2 -()大小写敏感
if (strpos($a, "are") !== false) {
echo "true"; // are Found
}
3- preg_match()
3 - preg_match()
if( preg_match("are",$a) === 1) {
echo "true"; // are Found
}
#24
12
Maybe you could use something like this:
也许你可以用这样的方法:
<?php
findWord('Test all OK');
function findWord($text) {
if (strstr($text, 'ok')) {
echo 'Found a word';
}
else
{
echo 'Did not find a word';
}
}
?>
#25
10
$a = 'how are you';
if (strpos($a,'are')) {
echo 'true';
}
#26
10
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)
如果您只想检查一个字符串是否包含在另一个字符串中,请不要使用preg_match()。使用strpos()或strstr()代替,因为它们将更快。(http://in2.php.net/preg_match)
if (strpos($text, 'string_name') !== false){
echo 'get the string';
}
#27
9
You need to use identical/not identical operators because strpos can return 0 as it's index value. If you like ternary operators, consider using the following (seems a little backwards I'll admit):
您需要使用相同/不同的操作符,因为strpos可以返回0作为它的索引值。如果你喜欢三元运算符,可以考虑使用下面的方法(我承认这有点落后):
echo FALSE === strpos($a,'are') ? 'false': 'true';
#28
9
If you want to check if the string contains several specifics words, you can do:
如果您想检查字符串是否包含几个具体的单词,您可以这样做:
$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";
}
This is useful to avoid spam when sending emails for example.
这对于在发送电子邮件时避免垃圾邮件是有用的。
#29
8
The strpos function works fine, but if you want to do case-insensitive
checking for a word in a paragraph then you can make use of the stripos
function of PHP
.
strpos函数可以正常工作,但是如果您想在段落中对一个单词进行不区分大小写的检查,那么您可以使用PHP的stripos函数。
For example,
例如,
$result = stripos("I love PHP, I love PHP too!", "php");
if ($result === false) {
// Word does not exist
}
else {
// Word exists
}
Find the position of the first occurrence of a case-insensitive substring in a string.
查找字符串中第一次出现不区分大小写的子字符串的位置。
If the word doesn't exist in the string then it will return false else it will return the position of the word.
如果字符串中不存在单词,那么它将返回false,否则它将返回单词的位置。
#30
8
Lot of answers that use substr_count
checks if the result is >0
. But since the if
statement considers zero the same as false, you can avoid that check and write directly:
大量的答案使用substr_count检查结果是否为>0。但由于if语句认为0与false相同,可以避免直接进行检查和写入:
if (substr_count($a, 'are')) {
To check if not present, add the !
operator:
要检查是否不存在,请添加!接线员:
if (!substr_count($a, 'are')) {