【发布时间】: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 吗?
-
这看起来很像一个序列化的字符串。如果您将其作为字符串访问,而不是反序列化并正确访问每个数据点,则可能会损坏数据以供将来处理。例如
27在2018/08/hello-there-003.jpg之前是因为那里有 27 个字符。