在 PHP 7.4 中,判断变量值是否为 uri 格式的数据
1、现在需要从一个一维数组中取出 uri 格式的数据。一维数组的打印结果,如图12、基于 filter_var 代码实现如下,打印结果如下,不符合预期,其中存在:internal://policy_pages/293、通过函数 parse_url 获取 scheme,判断是否为 http 或者 https。最后的过滤结果如下,符合预期。如图2
<pre class="wp-block-syntaxhighlighter-code">
array(134) {
[14]=>
bool(false)
[15]=>
string(0) ""
[16]=>
string(6) "center"
[17]=>
string(7) "#ffffff"
[18]=>
string(95) "https://xxx.s3.us-east-2.amazonaws.com/image/736589fac73c7dfdbf61efadb49a95fb9af16efb.jpeg"
[19]=>
string(30) "<p>Image with text overlay</p>"
[20]=>
string(8) "Shop Now"
}
</pre>
foreach ($images->all() as $image) {
var_dump($image, filter_var($image, FILTER_VALIDATE_URL));
echo "\n";
}
<pre class="wp-block-syntaxhighlighter-code">
string(11) "collections"
bool(false)
bool(false)
bool(false)
string(6) "center"
bool(false)
string(4) "grid"
bool(false)
string(18) "this is collection"
bool(false)
string(19) "main-index-carousel"
bool(false)
string(5) "slide"
bool(false)
bool(false)
bool(false)
string(0) ""
bool(false)
string(6) "center"
bool(false)
string(7) "#ffffff"
bool(false)
string(95) "https://xxx.us-east-2.amazonaws.com/image/736589fac73c7dfdbf61efadb49a95fb9af16efb.jpeg"
string(95) "https://xxx.us-east-2.amazonaws.com/image/736589fac73c7dfdbf61efadb49a95fb9af16efb.jpeg"
string(30) "<p>Image with text overlay</p>"
bool(false)
string(8) "Shop Now"
bool(false)
string(26) "internal://policy_pages/29"
string(26) "internal://policy_pages/29"
</pre>
$images = collect($data['sections'])->flatten()->reject(function ($image) {
return !filter_var($image, FILTER_VALIDATE_URL);
})->reject(function ($image) {
return !in_array(parse_url($image, PHP_URL_SCHEME), ['http', 'https']);
});
var_dump($images);
object(Illuminate\Support\Collection)#4918 (1) {
["items":protected]=>
array(4) {
[10]=>
string(107) "https://cdn.xxx.com/image/2022/04/fa5d91ba9fd60ef1b050560895d2f15c02852f0d9669654de4c01c8b404af3f3.jpeg"
[24]=>
string(95) "https://xxx.us-east-2.amazonaws.com/image/736589fac73c7dfdbf61efadb49a95fb9af16efb.jpeg"
[41]=>
string(95) "https://xxx.us-east-2.amazonaws.com/image/7a204816a9625475044c8196bfb154b39aa3f12b.jpeg"
[129]=>
string(95) "https://xxx.us-east-2.amazonaws.com/image/736589fac73c7dfdbf61efadb49a95fb9af16efb.jpeg"
}
}

