strpos에서 배열을 바늘로 사용
strpos
문자열을 검색 할 때 바늘 배열에를 어떻게 사용 합니까? 예를 들면 :
$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
if(strpos($string, $find_letters) !== false)
{
echo 'All the letters are found in the string!';
}
이거 사용하면 안 되니까 이런게 있으면 좋을 텐데
@Dave http://www.php.net/manual/en/function.strpos.php#107351 에서 업데이트 된 스 니펫
function strposa($haystack, $needles=array(), $offset=0) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle, $offset);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}
사용하는 방법:
$string = 'Whis string contains word "cheese" and "tea".';
$array = array('burger', 'melon', 'cheese', 'milk');
if (strposa($string, $array, 1)) {
echo 'true';
} else {
echo 'false';
}
true
때문에 반환됩니다 array
"cheese"
.
업데이트 : 바늘의 첫 번째 발견시 중지로 코드를 개선했습니다.
function strposa($haystack, $needle, $offset=0) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $query) {
if(strpos($haystack, $query, $offset) !== false) return true; // stop on first true result
}
return false;
}
$string = 'Whis string contains word "cheese" and "tea".';
$array = array('burger', 'melon', 'cheese', 'milk');
var_dump(strposa($string, $array)); // will return true, since "cheese" has been found
str_replace는 상당히 빠릅니다.
$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
$match = (str_replace($find_letters, '', $string) != $string);
아래 코드는이를 수행하는 방법을 보여줄뿐만 아니라 사용하기 쉬운 기능에 추가했습니다. "jesda"에 의해 작성되었습니다. (온라인에서 찾았습니다)
PHP 코드 :
<?php
/* strpos that takes an array of values to match against a string
* note the stupid argument order (to match strpos)
*/
function strpos_arr($haystack, $needle) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $what) {
if(($pos = strpos($haystack, $what))!==false) return $pos;
}
return false;
}
?>
용법:
$needle = array('something','nothing');
$haystack = "This is something";
echo strpos_arr($haystack, $needle); // Will echo True
$haystack = "This isn't anything";
echo strpos_arr($haystack, $needle); // Will echo False
배열을 반복하고을 strpos
반환하는 경우 "플래그"값을 설정할 수 있습니다 false
.
$flag = false;
foreach ($find_letters as $letter)
{
if (strpos($string, $letter) === false)
{
$flag = true;
}
}
그런 다음의 값을 확인하십시오 $flag
.
특정 문자가 실제로 문자열에 있는지 확인하려면 strtok 사용하십시오 .
$string = 'abcdefg';
if (strtok($string, 'acd') === $string) {
// not found
} else {
// found
}
이 표현식은 모든 문자를 검색합니다.
count(array_filter(
array_map("strpos", array_fill(0, count($letters), $str), $letters),
"is_int")) == count($letters)
질문은 제공된 예제가 단지 "예"일 뿐입니 까 아니면 정확히 찾고있는 것입니까? 여기에는 여러 가지 혼합 된 답변이 있으며 허용되는 답변의 복잡성을 이해하지 못합니다.
여부를 확인하려면 모든 컨텐츠 바늘의 배열이 문자열에 존재하고 신속하게 참 또는 거짓을 반환합니다 :
$string = 'abcdefg';
if(str_replace(array('a', 'c', 'd'), '', $string) != $string){
echo 'at least one of the needles where found';
};
그렇다면 @Leon 에게 크레딧을 제공하십시오 .
여부를 확인하려면 ALL의 값 바늘의 배열이 존재하는 이 경우에서와 같이 문자열에, 세 가지를 모두 'a', 'b'
하고 'c'
당신이 언급처럼, 존재해야합니다 귀하의 "예"로
echo '문자열에서 모든 글자를 찾았습니다!';
여기에 많은 답변이 그 맥락에서 벗어 났지만 해결 된 것으로 표시 한 질문의 의도가 의심됩니다. 예 : 허용되는 대답은 다음의 바늘입니다.
$array = array('burger', 'melon', 'cheese', 'milk');
모든 단어 가 문자열에서 반드시 발견되어야 한다면 ?
그런 다음 "not accepted answers"
이 페이지 에서 몇 가지를 시도해보십시오 .
이것을 시도 할 수 있습니다.
function in_array_strpos($word, $array){
foreach($array as $a){
if (strpos($word,$a) !== false) {
return true;
}
}
return false;
}
부정을 위해 strpbrk () 를 사용해 볼 수도 있습니다 (문자가 하나도 발견되지 않았습니다) :
$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
if(strpbrk($string, implode($find_letters)) === false)
{
echo 'None of these letters are found in the string!';
}
This is my approach. Iterate over characters in the string until a match is found. On a larger array of needles this will outperform the accepted answer because it doesn't need to check every needle to determine that a match has been found.
function strpos_array($haystack, $needles = [], $offset = 0) {
for ($i = $offset, $len = strlen($haystack); $i < $len; $i++){
if (in_array($haystack[$i],$needles)) {
return $i;
}
}
return false;
}
I benchmarked this against the accepted answer and with an array of more than 7 $needles
this was dramatically faster.
With the following code:
$flag = true;
foreach($find_letters as $letter)
if(false===strpos($string, $letter)) {
$flag = false;
break;
}
Then check the value of $flag
. If it is true
, all letters have been found. If not, it's false
.
I'm writing a new answer which hopefully helps anyone looking for similar to what I am.
This works in the case of "I have multiple needles and I'm trying to use them to find a singled-out string". and this is the question I came across to find that.
$i = 0;
$found = array();
while ($i < count($needle)) {
$x = 0;
while ($x < count($haystack)) {
if (strpos($haystack[$x], $needle[$i]) !== false) {
array_push($found, $haystack[$x]);
}
$x++;
}
$i++;
}
$found = array_count_values($found);
The array $found
will contain a list of all the matching needles, the item of the array with the highest count value will be the string(s) you're looking for, you can get this with:
print_r(array_search(max($found), $found));
Reply to @binyamin and @Timo.. (not enough points to add a comment..) but the result doesn't contain the position..
The code below will return the actual position of the first element which is what strpos is intended to do. This is useful if you're expecting to find exactly 1 match.. If you're expecting to find multiple matches, then position of first found may be meaningless.
function strposa($haystack, $needle, $offset=0) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $query) {
$res=strpos($haystack, $query, $offset);
if($res !== false) return $res; // stop on first true result
}
return false;
}
Just an upgrade from above answers
function strsearch($findme, $source){
if(is_array($findme)){
if(str_replace($findme, '', $source) != $source){
return true;
}
}else{
if(strpos($source,$findme)){
return true;
}
}
return false;
}
참고URL : https://stackoverflow.com/questions/6284553/using-an-array-as-needles-in-strpos
'Nice programing' 카테고리의 다른 글
Jquery Ajax 오류 처리가 중단됨을 무시합니다. (0) | 2020.10.14 |
---|---|
객체 PHP의 모든 속성을 반복 (0) | 2020.10.14 |
C #에서 잘못된 XML 문자 이스케이프 (0) | 2020.10.13 |
내 C # WinForm 응용 프로그램을 어떻게 다시 시작합니까? (0) | 2020.10.13 |
Node.js를 통해 Amazon S3에 base64 인코딩 이미지 업로드 (0) | 2020.10.13 |