PHP 字符串中的数组值?
我已经在 PHP 手册中查找了一段时间,但找不到任何可以完成我想要的命令。
我有一个包含键和值的数组,例如:
$Fields = array("Color"=>"Bl","Taste"=>"Good","Height"=>"Tall");
然后我有一个字符串,例如:
$Headline = "My black coffee is cold";
现在我想找出是否有任何数组($Fields)值与字符串($Headline)中的某个位置匹配。
示例:
Array_function_xxx($Headline,$Fields);
结果为 true,因为“bl”位于字符串 $Headline 中(作为“Black”的一部分)。
我问是因为我需要性能...如果这是不可能的,我只会制作自己的函数...
编辑 - 我正在寻找类似 stristr(string $haystack ,数组 $needle);
谢谢
解决方案 - 我想出了他的功能。
function array_in_str($fString, $fArray) {
$rMatch = array();
foreach($fArray as $Value) {
$Pos = stripos($fString,$Value);
if($Pos !== false)
// Add whatever information you need
$rMatch[] = array( "Start"=>$Pos,
"End"=>$Pos+strlen($Value)-1,
"Value"=>$Value
);
}
return $rMatch;
}
返回的数组现在包含有关每个匹配单词的开始和结束位置的信息。
I have been looking around for a while in the PHP manual and can't find any command that does what I want.
I have an array with Keys and Values, example:
$Fields = array("Color"=>"Bl","Taste"=>"Good","Height"=>"Tall");
Then I have a string, for example:
$Headline = "My black coffee is cold";
Now I want to find out if any of the array ($Fields) values match somewhere in the string ($Headline).
Example:
Array_function_xxx($Headline,$Fields);
Would give the result true because "bl" is in the string $Headline (as a part of "Black").
I'm asking because I need performance... If this isn't possible, I will just make my own function instead...
EDIT - I'm looking for something like stristr(string $haystack , array $needle);
Thanks
SOLUTION - I came up with his function.
function array_in_str($fString, $fArray) {
$rMatch = array();
foreach($fArray as $Value) {
$Pos = stripos($fString,$Value);
if($Pos !== false)
// Add whatever information you need
$rMatch[] = array( "Start"=>$Pos,
"End"=>$Pos+strlen($Value)-1,
"Value"=>$Value
);
}
return $rMatch;
}
The returning array now have information on where each matched word begins and ends.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该有所帮助:
将函数的名称替换为您需要的名称。
编辑:
好的,替代解决方案(可能提供更好的性能,允许不区分大小写的搜索,但需要 $fields 参数中的正确值)是:
This should help:
Replace name of the function with what you need.
EDIT:
Ok, alternative solution (probably giving better performance, allowing for case-insensitive search, but requiring proper values within $fields parameter) is:
http://www.php.net/manual/en/function.array -搜索.php
这就是您
从 php.net 寻找的示例
http://www.php.net/manual/en/function.array-search.php
that's what you looking for
example from php.net