문자열에 배열에 값이 포함되어 있는지 확인합니다.
문자열에 배열에 저장된 URL이 하나 이상 포함되어 있는지 확인하려고 합니다.
어레이는 다음과 같습니다.
$owned_urls = array('website1.com', 'website2.com', 'website3.com');
문자열은 사용자가 입력하고 PHP를 통해 제출됩니다.확인 페이지에서 입력한 URL이 배열에 있는지 확인하고 싶습니다.
다음을 시도했습니다.
$string = 'my domain name is website3.com';
if (in_array($string, $owned_urls))
{
echo "Match found";
return true;
}
else
{
echo "Match not found";
return false;
}
입력된 내용에 관계없이 반환은 항상 "일치하지 않음"입니다.
이게 올바른 방법인가요?
이거 먹어봐.
$string = 'my domain name is website3.com';
foreach ($owned_urls as $url) {
//if (strstr($string, $url)) { // mine version
if (strpos($string, $url) !== FALSE) { // Yoshi version
echo "Match found";
return true;
}
}
echo "Not found!";
return false;
대소문자를 구분하지 않을 경우 stristr() 또는 stripos()를 사용합니다.
배열에서 문자열을 찾는 것만을 원하는 경우 이 작업은 훨씬 더 쉬워졌습니다.
$array = ["they has mystring in it", "some", "other", "elements"];
if (stripos(json_encode($array),'mystring') !== false) {
echo "found mystring";
}
이것을 시험해 보세요.
$owned_urls= array('website1.com', 'website2.com', 'website3.com');
$string = 'my domain name is website3.com';
$url_string = end(explode(' ', $string));
if (in_array($url_string,$owned_urls)){
echo "Match found";
return true;
} else {
echo "Match not found";
return false;
}
- 감사합니다. -감사합니다.
여기서는 카운트 파라미터로 심플하게 동작합니다.
$count = 0;
str_replace($owned_urls, '', $string, $count);
// if replace is successful means the array value is present(Match Found).
if ($count > 0) {
echo "One of Array value is present in the string.";
}
상세정보 - https://www.techpurohit.in/extended-behaviour-explode-and-strreplace-php
preg_match를 사용하는 것이 더 빠른 방법이라고 생각합니다.
$user_input = 'Something website2.com or other';
$owned_urls_array = array('website1.com', 'website2.com', 'website3.com');
if ( preg_match('('.implode('|',$owned_urls_array).')', $user_input)){
echo "Match found";
}else{
echo "Match not found";
}
$string = 'my domain name is website3.com';
$a = array('website1.com','website2.com','website3.com');
$result = count(array_filter($a, create_function('$e','return strstr("'.$string.'", $e);')))>0;
var_dump($result );
산출량
bool(true)
여기에서는 지정된 문자열의 배열에서 모든 값을 검색하는 미니 함수를 보여 줍니다.내 사이트에서 방문자 IP가 특정 페이지의 허용 목록에 있는지 확인하기 위해 사용합니다.
function array_in_string($str, array $arr) {
foreach($arr as $arr_value) { //start looping the array
if (stripos($str,$arr_value) !== false) return true; //if $arr_value is found in $str return true
}
return false; //else return false
}
사용법
$owned_urls = array('website1.com', 'website2.com', 'website3.com');
//this example should return FOUND
$string = 'my domain name is website3.com';
if (array_in_string($string, $owned_urls)) {
echo "first: Match found<br>";
}
else {
echo "first: Match not found<br>";
}
//this example should return NOT FOUND
$string = 'my domain name is website4.com';
if (array_in_string($string, $owned_urls)) {
echo "second: Match found<br>";
}
else {
echo "second: Match not found<br>";
}
데모: http://phpfiddle.org/lite/code/qf7j-8m09
stripos 기능은 그다지 엄격하지 않습니다.대소문자를 구분하지 않거나 단어의 일부와 일치할 수 있습니다.http://php.net/manual/ro/function.stripos.php
검색에서 대소문자를 구분하려면 strpos http://php.net/manual/ro/function.strpos.php 를 사용합니다.
regex(preg_match)를 정확하게 일치시키려면 이 사람이 https://stackoverflow.com/a/25633879/4481831에 응답하는지 확인하십시오.
배열 값을 innode 및 | 구분 기호로 연결한 다음 preg_match를 사용하여 값을 검색할 수 있습니다.
여기 제가 생각해낸 해결책이 있습니다.
$emails = array('@gmail', '@hotmail', '@outlook', '@live', '@msn', '@yahoo', '@ymail', '@aol');
$emails = implode('|', $emails);
if(!preg_match("/$emails/i", $email)){
// do something
}
의 '' ''가$string
항상 일관성이 있습니다(즉,도메인 이름은 항상 문자열 끝에 있습니다).explode()
end()
「」를 합니다.in_array()
(@Anand Solanki) @Anand Solanki입니다.
않으면 정규 , 이 문자열에서 도메인을 추출하는 것이 in_array()
일치하는지 확인합니다.
$string = 'There is a url mysite3.com in this string';
preg_match('/(?:http:\/\/)?(?:www.)?([a-z0-9-_]+\.[a-z0-9.]{2,5})/i', $string, $matches);
if (empty($matches[1])) {
// no domain name was found in $string
} else {
if (in_array($matches[1], $owned_urls)) {
// exact match found
} else {
// exact match not found
}
}
위의 표현은 개선될 수 있을 것 같습니다(저는 이 분야에 대해 잘 모릅니다).
여기 데모가 있습니다.
$owned_urls= array('website1.com', 'website2.com', 'website3.com');
$string = 'my domain name is website3.com';
for($i=0; $i < count($owned_urls); $i++)
{
if(strpos($string,$owned_urls[$i]) != false)
echo 'Found';
}
배열 값에 대한 전체 문자열을 검사하고 있습니다.그래서 출력은 항상false
.
둘 다 사용해요.array_filter
그리고.strpos
이 경우는,
<?php
$urls= array('website1.com', 'website2.com', 'website3.com');
$string = 'my domain name is website3.com';
$check = array_filter($urls, function($url){
global $string;
if(strpos($string, $url))
return true;
});
echo $check?"found":"not found";
$message = "This is test message that contain filter world test3";
$filterWords = array('test1', 'test2', 'test3');
$messageAfterFilter = str_replace($filterWords, '',$message);
if( strlen($messageAfterFilter) != strlen($message) )
echo 'message is filtered';
else
echo 'not filtered';
루프를 돌리지 않고 빠르고 간단하게 할 수 있습니다.
$array = array("this", "that", "there", "here", "where");
$string = "Here comes my string";
$string2 = "I like to Move it! Move it";
$newStr = str_replace($array, "", $string);
if(strcmp($string, $newStr) == 0) {
echo 'No Word Exists - Nothing got replaced in $newStr';
} else {
echo 'Word Exists - Some Word from array got replaced!';
}
$newStr = str_replace($array, "", $string2);
if(strcmp($string2, $newStr) == 0) {
echo 'No Word Exists - Nothing got replaced in $newStr';
} else {
echo 'Word Exists - Some Word from array got replaced!';
}
작은 설명!
새 변수 만들기:
$newStr
원래 문자열 배열의 값을 바꿉니다.문자열 비교 실행 - 값이 0인 경우 문자열은 동일하고 대체되지 않았음을 의미하므로 배열 값이 문자열에 없습니다.
2의 반대일 경우, 즉 문자열 비교 실행 중 원본 문자열과 새 문자열이 모두 일치하지 않았습니다. 즉, 무엇인가가 대체되었기 때문에 배열 값이 문자열에 존재합니다.
$search = "web"
$owned_urls = array('website1.com', 'website2.com', 'website3.com');
foreach ($owned_urls as $key => $value) {
if (stristr($value, $search) == '') {
//not fount
}else{
//found
}
이것은 대소문자를 구분하지 않고 빠른 서브스트링에 대한 최선의 접근법 검색입니다.
im mysql처럼
예:
테이블에서 *를 선택합니다. 여기서 name = "%web%"
이 기능을 생각해 냈습니다.이 기능이 누군가에게 도움이 되었으면 합니다.
$word_list = 'word1, word2, word3, word4';
$str = 'This string contains word1 in it';
function checkStringAgainstList($str, $word_list)
{
$word_list = explode(', ', $word_list);
$str = explode(' ', $str);
foreach ($str as $word):
if (in_array(strtolower($word), $word_list)) {
return TRUE;
}
endforeach;
return false;
}
또한 일치하는 워드가 다른 워드의 일부일 경우 strpos()로 응답하면 true가 반환됩니다.예를 들어 단어 목록에 'st'가 포함되어 문자열에 'street'이 포함되어 있으면 strpos()는 true를 반환합니다.
언급URL : https://stackoverflow.com/questions/19445798/check-if-string-contains-a-value-in-array
'itsource' 카테고리의 다른 글
$_SERVER['] 없이 HTTPS를 사용하고 있는지 확인하는 방법HTTPS'] (0) | 2022.09.21 |
---|---|
변수 초기화, 정의, 선언 간의 차이 (0) | 2022.09.21 |
명령줄의 소스를 사용하여 Maven 아티팩트를 설치하는 방법은 무엇입니까? (0) | 2022.09.21 |
MySQL/Amazon RDS 오류: "SUPER 권한이 없습니다.." (0) | 2022.09.21 |
innerText와 inner의 차이HTML과 가치? (0) | 2022.09.21 |