[英]How to fully retrieve a URL from an array if it matches a specific string with PHP
如何通過包含多個 URL 的數組搜索和檢索包含特定字符串(包含在變量中)的 URL?
我嘗試了幾個函數,包括 array_intersect,但匹配必須與這個函數完美匹配。
我找到的唯一方法是 preg_match_all 但我是 PHP 的新手,我不知道應該向 preg_match_all 函數添加什么確切的正則表達式和參數,你能幫我嗎?
array() {
[0]=>
string(45) "http://localhost/website02/wp-content/uploads/2022/12/2023-lamborghini-huracan-sterrato-1-2.jpg"
[1]=>
string(100) "http://localhost/website02/wp-content/uploads/2022/12/alpine-a4810-hydrogen-concept-front-corner.jpg"
[2]=>
string(74) "http://localhost/website02/wp-content/uploads/2022/12/lexus-example-1.jpg"
}
$mystring = "example";
$pattern = "/$mystring/i";
if(preg_match($pattern, $arr, $matches)) {
print_r($matches[0][1]);
/************ I would like the result: http://localhost/website02/wp-content/uploads/2022/12/lexus-example-1.jpg *****************/
}
您可以試試這段代碼,這將返回匹配“example”的 url
$array = ['http://localhost/website02/wp-content/uploads/2022/12/2023-lamborghini-huracan-sterrato-1-2.jpg','http://localhost/website02/wp-content/uploads/2022/12/alpine-a4810-hydrogen-concept-front-corner.jpg','http://localhost/website02/wp-content/uploads/2022/12/lexus-example-1.jpg'];
foreach($array as $url)
{
$baseName = basename($url);
$str_arr = preg_split ("/\-/", $baseName);
foreach($str_arr as $value)
{
if(preg_match('/example/i', $value))
{
echo $url;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.