【问题标题】:How to find all jpgs with possible hyphens without http?如何在没有http的情况下找到所有带有可能连字符的jpg?
【发布时间】:2018-10-17 20:44:30
【问题描述】:

如果你有这个字符串:

$str = ';s:27:"2018/08/hello-there-003.jpg";s:5:"sizes";a:23:{s:9:"thumbnail";a:4:{s:4:"file";s:27:"hello-there-003-150x150.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:27:"hello-there-003-300x200.jpg"';

是否可以从中获取所有 jpg 并将其替换为其他内容?

匹配项应该是:

hello-there-003-150x150.jpg
hello-there-003-300x200.jpg

并替换为:

replacement.jpg
replacement.jpg

所以结果字符串是:

 $str = ';s:27:"2018/08/replacement.jpg";s:5:"sizes";a:23:{s:9:"thumbnail";a:4:{s:4:"file";s:27:"replacement.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:27:"hello-there-003-300x200.jpg"';

【问题讨论】:

  • regex101.com 更简单的正则表达式更好。也许将字符串解析为令牌,按摩关键部分,然后重新组装令牌。
  • (? regex101.com/r/2xgKUz/1,如果它适合你,我可以添加为答案。替换它,你会做编码,这在你身上。
  • 看起来像一个破碎的灭菌阵列
  • 卢卡斯,完美!但是您将如何替换字符串中的结果?哦,你说那是我的问题,但是方法是什么,是 foreach 循环和 str_replace 吗?
  • 这看起来很像一个序列化的字符串。如果您将其作为字符串访问,而不是反序列化并正确访问每个数据点,则可能会损坏数据以供将来处理。例如272018/08/hello-there-003.jpg 之前是因为那里有 27 个字符。

标签: php regex


【解决方案1】:

对于您的示例数据,您可以使用:

"\K[\w-]+(\.jpg)(?=")

Regex demo

替换为

replacement$1

说明

  • "匹配“
  • \K忘记匹配的内容
  • [\w-]+ 匹配一个单词字符或连字符 1+ 次
  • (\.jpg) 在捕获组中匹配 .jpg
  • (?=") 正向前瞻断言右侧的内容是双引号

例如:

$re = '/"\K[\w-]+(\.jpg)(?=")/';
$str = ';s:27:"2018/08/hello-there-003.jpg";s:5:"sizes";a:23:{s:9:"thumbnail";a:4:{s:4:"file";s:27:"hello-there-003-150x150.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:27:"hello-there-003-300x200.jpg"
';
$subst = 'replacement$1';
$result = preg_replace($re, $subst, $str);

echo $result;

Php demo

【讨论】:

    猜你喜欢
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多