Cha*_*ung 2663 php string substring contains string-matching
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
Run Code Online (Sandbox Code Playgroud)
假设我有上面的代码,编写语句的正确方法是什么if ($a contains 'are')
?
cod*_*ict 6534
您可以使用strpos()
用于在另一个字符串中查找一个字符串的出现的函数:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
Run Code Online (Sandbox Code Playgroud)
注意使用!== false
是故意的; != false
返回针字符串在haystack字符串中开始的偏移量,=== true
如果未找到针,则返回布尔值.由于0是有效偏移量而0是"假",因此我们不能使用更简单的结构strpos()
.
Bre*_*zer 573
您可以使用正则表达式,与其他用户提到的strpos相比,它更适合单词匹配,对于诸如票价,关心,凝视等字符串也会返回true.这可以通过使用单词边界在正则表达式中简单地避免.
一个简单的匹配可能看起来像这样:
$a = 'How are you?';
if (preg_match('/\bare\b/', $a)) {
echo 'true';
}
Run Code Online (Sandbox Code Playgroud)
在性能方面,strpos的速度提高了大约三倍,并且考虑到,当我同时进行一百万次比较时,strpos
完成需要1.5秒,而strpos需要0.5秒.
编辑:为了搜索字符串的任何部分,而不是逐字逐句,我建议使用正则表达式
$a = 'How are you?';
$search = 'are y';
if(preg_match("/{$search}/i", $a)) {
echo 'true';
}
Run Code Online (Sandbox Code Playgroud)
将strpos
在正则表达式的结尾改变正则表达式是区分大小写的,如果你不希望出现这种情况,你可以离开它.
现在这在某些情况下可能会出现问题,因为$ search字符串在任何情况下都没有消毒,我的意思是,在某些情况下它可能无法通过检查,好像preg_match
是用户输入它们可以添加一些可能表现得像某些不同的字符串正则表达式...
此外,这是一个很好的工具,用于测试和查看各种正则表达式Regex101的解释
eju*_*ker 244
这是一个小实用函数,在这种情况下很有用
// returns true if $needle is a substring of $haystack
function contains($needle, $haystack)
{
return strpos($haystack, $needle) !== false;
}
Run Code Online (Sandbox Code Playgroud)
FtD*_*Xw6 133
虽然这些答案中的大多数都会告诉您字符串中是否出现子字符串,但如果您要查找特定单词而不是子字符串,则通常不是您想要的.
有什么不同?子字符串可以出现在其他词语中:
减轻这种情况的一种方法是使用与单词边界(\b
)相结合的正则表达式:
function containsWord($str, $word)
{
return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i', $str);
}
Run Code Online (Sandbox Code Playgroud)
这种方法没有上面提到的相同误报,但它确实有一些自己的边缘情况.单词边界匹配非单词字符(\W
),这将是任何不是a-z
,A-Z
,0-9
,或_
.这意味着数字和下划线将被计为单词字符,这样的场景将失败:
如果你想要比这更精确的东西,你将不得不开始进行英语语法语法分析,这是一个非常大的蠕虫(并假设正确使用语法,无论如何,这并不总是给定).
Jos*_*ega 120
要确定字符串是否包含另一个字符串,可以使用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";
}
?>
Run Code Online (Sandbox Code Playgroud)
警告:
如果您要搜索的针头位于干草堆的开头,它将返回位置0,如果您进行的==
比较不起作用,则需要执行===
甲==
符号是比较和试验可变/表达/常数向左是否具有相同的值作为变量/表达/恒定到右侧.
一个===
标志是一个比较,看两个变量/ expresions /常量是否相等AND
具有相同类型的-即两个都是字符串或都是整数.
Hai*_*vgi 62
<?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.";
}
?>
Run Code Online (Sandbox Code Playgroud)
Raf*_*shi 43
同意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;
}
Run Code Online (Sandbox Code Playgroud)
情况1
$query = 'are';
$corpus = array(
1 => 'How are you?',
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)
结果
Array
(
[1] => 0.52832083357372
)
Run Code Online (Sandbox Code Playgroud)
案例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>';
Run Code Online (Sandbox Code Playgroud)
结果
Array
(
[1] => 0.54248125036058
[3] => 0.21699250014423
)
Run Code Online (Sandbox Code Playgroud)
案例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>';
Run Code Online (Sandbox Code Playgroud)
结果
Array
(
[3] => 0.6813781191217
[1] => 0.54248125036058
)
Run Code Online (Sandbox Code Playgroud)
有很多的改进,进行但该模型提供了获得自然查询,这没有布尔运算符,如良好的效果的一种方式strpos()
,preg_match()
,strstr()
或stristr()
.
NOTA BENE
可选地在搜索单词之前消除冗余
从而减少了索引大小并减少了存储需求
减少磁盘I/O.
更快的索引和更快的搜索.
1.规范化
2.删除词汇
3.字典替换
将词语替换为具有相同或相似含义的其他词语.(例如:用'饥饿'代替'饥饿'和'饥饿'的例子)
可以执行进一步的算法测量(滚雪球)以进一步将单词减少到其本质含义.
用十六进制等效替换颜色名称
通过降低精度来减少数值是标准化文本的其他方法.
资源
Sha*_*ran 41
使用不区分大小写匹配使用stripos()
:
if (stripos($string,$stringToSearch) !== false) {
echo 'true';
}
Run Code Online (Sandbox Code Playgroud)
Ala*_*lla 39
如果你想避免"假"和"真理"问题,你可以使用substr_count:
if (substr_count($a, 'are') > 0) {
echo "at least one 'are' is present!";
}
Run Code Online (Sandbox Code Playgroud)
它比strpos慢一点,但它避免了比较问题.
Yas*_*G99 29
另一种选择是使用strstr()函数.就像是:
if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}
Run Code Online (Sandbox Code Playgroud)
注意:strstr()函数区分大小写.对于不区分大小写的搜索,请使用stristr()函数.
joa*_*16v 28
if (preg_match('/(are)/', $a)) {
echo 'true';
}
Run Code Online (Sandbox Code Playgroud)
Arm*_*oot 27
我有点印象,这里没有使用的答案strpos
,strstr
类似的功能提到了多字节字符串函数(2015-05-08).
基本上,如果您在查找某些语言特有的字词时遇到问题,例如德语,法语,葡萄牙语,西班牙语等(例如:ä,é,ô,ç,º,ñ),您可能需要先于功能与mb_
.因此,接受的答案将使用mb_strpos
或mb_stripos
(对于不区分大小写的匹配):
if (mb_strpos($a,'are') !== false) {
echo 'true';
}
Run Code Online (Sandbox Code Playgroud)
如果您无法保证所有数据都是100%UTF-8,则可能需要使用这些mb_
功能.
一篇很好的文章,了解为什么绝对最低限度每个软件开发人员必须知道关于Unicode和字符集(没有借口!)的Joel Spolsky.
Joh*_*ers 24
在PHP中,验证字符串是否包含某个子字符串的最佳方法是使用这样的简单辅助函数:
function contains($haystack, $needle, $caseSensitive = false) {
return $caseSensitive ?
(strpos($haystack, $needle) === FALSE ? FALSE : TRUE):
(stripos($haystack, $needle) === FALSE ? FALSE : TRUE);
}
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
Jas*_*OOO 21
以下功能也有效,不依赖于任何其他功能; 它仅使用本机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;
}
}
Run Code Online (Sandbox Code Playgroud)
测试:
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
Run Code Online (Sandbox Code Playgroud)
Ars*_* KV 20
你可以使用这个strstr
功能:
$haystack = "I know programming";
$needle = "know";
$flag = strstr($haystack, $needle);
if ($flag){
echo "true";
}
Run Code Online (Sandbox Code Playgroud)
不使用内置函数:
$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 ";
}
Run Code Online (Sandbox Code Playgroud)
Dec*_*bal 19
我遇到了一些麻烦,最后我选择创建自己的解决方案.不使用正则表达式引擎:
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;
}
Run Code Online (Sandbox Code Playgroud)
您可能会注意到,之前的解决方案不是将该词用作另一个词的前缀的答案.为了使用你的例子:
$a = 'How are you?';
$b = "a skirt that flares from the waist";
$c = "are";
Run Code Online (Sandbox Code Playgroud)
使用上面的示例,包含$a
和$b
包含$c
,但您可能希望您的功能告诉您仅$a
包含$c
.
Sad*_*san 16
使用strstr()和stristr()从字符串中查找单词出现的另一个选项如下所示:
<?php
$a = 'How are you?';
if (strstr($a,'are')) // Case sensitive
echo 'true';
if (stristr($a,'are')) // Case insensitive
echo 'true';
?>
Run Code Online (Sandbox Code Playgroud)
Sha*_*ngh 14
它可以通过三种不同的方式完成:
$a = 'How are you?';
Run Code Online (Sandbox Code Playgroud)
1- stristr()
if (strlen(stristr($a,"are"))>0) {
echo "true"; // are Found
}
Run Code Online (Sandbox Code Playgroud)
2- strpos()
if (strpos($a, "are") !== false) {
echo "true"; // are Found
}
Run Code Online (Sandbox Code Playgroud)
3- preg_match()
if( preg_match("are",$a) === 1) {
echo "true"; // are Found
}
Run Code Online (Sandbox Code Playgroud)
T30*_*T30 14
substr_count
如果结果是,使用检查的很多答案>0
.但由于if
语句将false视为false,因此可以避免直接检查和写入:
if (substr_count($a, 'are')) {
Run Code Online (Sandbox Code Playgroud)
要检查是否不存在,请添加!
运算符:
if (!substr_count($a, 'are')) {
Run Code Online (Sandbox Code Playgroud)
Som*_*atd 13
简易版
$result = false!==strpos($a, 'are');
Run Code Online (Sandbox Code Playgroud)
DJC*_*DJC 13
为了找到一个"单词",而不是出现一系列可能实际上是另一个单词的一部分的字母,以下将是一个很好的解决方案.
$string = 'How are you?';
$array = explode(" ", $string);
if (in_array('are', $array) ) {
echo 'Found the word';
}
Run Code Online (Sandbox Code Playgroud)
Pra*_*tik 12
您应该使用大小写不敏感的格式,因此如果输入的值在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";
}
?>
Run Code Online (Sandbox Code Playgroud)
这里stripos在heystack中找到针,而不考虑案例(小/帽).
Mat*_*rou 12
也许你可以使用这样的东西:
<?php
findWord('Test all OK');
function findWord($text) {
if (strstr($text, 'ok')) {
echo 'Found a word';
}
else
{
echo 'Did not find a word';
}
}
?>
Run Code Online (Sandbox Code Playgroud)
Vin*_*shi 11
preg_match()
如果您只想检查另一个字符串中是否包含一个字符串,请不要使用.使用strpos()
或strstr()
替代,因为它们会更快.(http://in2.php.net/preg_match)
if (strpos($text, 'string_name') !== false){
echo 'get the string';
}
Run Code Online (Sandbox Code Playgroud)
Jul*_*ien 10
如果要检查字符串是否包含多个特定单词,您可以执行以下操作:
$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";
}
Run Code Online (Sandbox Code Playgroud)
例如,这有助于在发送电子邮件时避免垃圾邮件.
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
}
Run Code Online (Sandbox Code Playgroud)
查找字符串中第一次出现不区分大小写的子字符串的位置.
如果字符串中不存在该单词,则它将返回false,否则它将返回该单词的位置.
您需要使用相同/不相同的运算符,因为strpos可以返回0作为其索引值.如果您喜欢三元运算符,请考虑使用以下内容(似乎有点倒退我会承认):
echo FALSE === strpos($a,'are') ? 'false': 'true';
Run Code Online (Sandbox Code Playgroud)
检查字符串是否包含特定单词?
这意味着必须将字符串解析为单词(请参阅下面的注释).
执行此操作和指定分隔符的一种方法是使用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');
?>
Run Code Online (Sandbox Code Playgroud)
跑步给出了
$ 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'
Run Code Online (Sandbox Code Playgroud)
注意:这里我们不是指每个符号序列的单词.
词的实际定义在某种意义上是PCRE正则表达式引擎,其中单词是仅由单词字符组成的子串,由非单词字符分隔.
"单词"字符是任何字母或数字或下划线字符,即任何可以成为Perl"单词"一部分的字符.字母和数字的定义由PCRE的字符表控制,如果发生特定于区域设置的匹配,则可能会有所不同(..)
小智 7
您还可以使用内置的功能strchr()
和strrchr()
和扩展多字节字符串mb_strchr()
和mb_strrchr()
。这些函数返回字符串的一部分,FALSE
如果没有找到。
strchr()
- 查找字符串的第一次出现(是 的别名strstr()
)。strrchr()
- 查找字符串中最后一次出现的字符。 可以使用以下函数检查字符串:
function either_String_existor_not($str, $character) {
if (strpos($str, $character) !== false) {
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
我认为一个好主意是使用mb_stpos
:
$haystack = 'How are you?';
$needle = 'are';
if (mb_strpos($haystack, $needle) !== false) {
echo 'true';
}
Run Code Online (Sandbox Code Playgroud)
因为此解决方案区分大小写并且对所有 Unicode 字符都是安全的。
但是你也可以这样做(目前还没有回应):
if (count(explode($needle, $haystack)) > 1) {
echo 'true';
}
Run Code Online (Sandbox Code Playgroud)
此解决方案对 Unicode 字符也区分大小写且安全。
此外,不要在表达式中使用否定,这会增加代码的可读性。
这是使用函数的其他解决方案:
function isContainsStr($haystack, $needle) {
return count(explode($needle, $haystack)) > 1;
}
if (isContainsStr($haystack, $needle)) {
echo 'true';
}
Run Code Online (Sandbox Code Playgroud)
特定字符串的另一种解决方案:
$subject = 'How are you?';
$pattern = '/are/';
preg_match($pattern, $subject, $match);
if ($match[0] == 'are') {
echo true;
}
Run Code Online (Sandbox Code Playgroud)
你也可以使用strpos()
功能.
使用:
$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";
}
Run Code Online (Sandbox Code Playgroud)
小智 5
用:
$a = 'How are you?';
if (mb_strpos($a, 'are')) {
echo 'true';
}
Run Code Online (Sandbox Code Playgroud)
它执行多字节安全 strpos() 操作。
小智 5
一个更简单的选择:
return ( ! empty($a) && strpos($a, 'are'))? true : false;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4708520 次 |
最近记录: |