【问题标题】:PHP: Regex JSON file for image namesPHP:图像名称的正则表达式 JSON 文件
【发布时间】:2019-04-12 09:39:48
【问题描述】:

我正在尝试从 json 文件中获取所有图像名称和扩展名。

目前我有以下模式:

$pattern = '/(.*).jpg/i';

当我为此运行 php 时,我得到以下输出:

[1506] => "saturday.jpg
[1507] => "friday.jpg
[1508] => "monday.jpg
[1518] => "image": "ten-pound.jpg
[1519] => "image": "hundred-fifty-pounds.jpg
[1520] => "image": "six-pound-fifty.jpg
[1568] => "answer": "thursday.jpg
[1633] => "answer": "london.jpg

除了图像名称我什么都不想要。所以不是"image""answer":,甚至不是开头"

我最理想的是将所有图像输出到这样的数组中:

$images = {"saturday.jpg","monday.jpg","ten-pound.jpg"}

有什么想法吗?

【问题讨论】:

  • 您能告诉我们原始 JSON 的样子吗?
  • 当然,等一下。
  • 试试$pattern = '/[^\s"]+\.jpg/i'。如果 URL 中有空格,它将不起作用。它还将匹配具有 1+ 个字符而不是空格和 " 后跟 .jpg 的任何匹配文本,因此结果可能不是您所期望的。
  • @WiktorStribiżew - 哇,好用。谢谢 - 想添加它作为答案,我可以接受吗?
  • 请添加您拥有的示例 JSON,也许有更好的解决方案。

标签: php json regex


【解决方案1】:

要修复您的正则表达式方法,您只需在 .jpg 之前匹配除空格和 " 之外的任何 1 个或多个字符(请注意,必须对 . 进行转义以匹配文字点):

$pattern = '/[^\s"]+\.jpg/i'

this regex demo

您可以通过简单地遍历 JSON 键值数组并以不区分大小写的方式获取以 .jpg 结尾的每个值来实现您想要的目标

$json = '{"k": {"image": "monday.jpg"}, "k2" : {"image": "ten-pound.jpg"},  "k3": {"image": "hundred-fifty-pounds.jpg"}}';
$j = json_decode($json, true);
$results=[];
function json_recursion($myarray, $needle, &$results = array())
{
    foreach ($myarray as $key => $value)
    {
            if (is_array($value)) {
                json_recursion($value, $needle, $results);
            } else if (substr(strtoupper($value), -strlen($needle)) === strtoupper($needle)) {
                $results[] = $value;
            }
    }
}
json_recursion($j, ".jpg", $results);
print_r($results);

PHP demo 的输出:

Array
(
    [0] => monday.jpg
    [1] => ten-pound.jpg
    [2] => hundred-fifty-pounds.jpg
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 2011-09-27
    相关资源
    最近更新 更多