替换 PHP 中字符串中出现的所有文本模式


Replace all occurrences of a text pattern within a string in PHP

我有一个字符串,其中包含许多具有各种图像大小的wordpress图像名称。例如:

imgr-3sdfsdf9-266x200.png, pics-asf39-266x800.png, ruh-39-150x200.png

我需要做的是将这种字符串中的所有图像大小替换为字符串"150x150"。该字符串可能有数百个不同大小的不同文件名。到目前为止,所有尺寸的格式都是 dddxddd - 3 位数字由"x"后跟另外 3 位数字组成。我不认为我会有 4 位数字的宽度或高度。始终,大小就在.png扩展之前。所以在处理了上面提到的字符串后,它应该变成这样:

imgr-3sdfsdf9-150x150.png, pics-asf39-150x150.png, ruh-39-150x150.png

任何帮助将不胜感激。

$size = 150;
echo preg_replace(
  '#'d{3,4}x'd{3,4}'.#is',
  "{$size}x{$size}.",
  'imgr-3sdfsdf9-266x200.png, pics-asf39-266x800.png, ruh-39-150x200.png'
);

这将是这样的:

$string = 'imgr-3sdfsdf9-266x200.png, pics-asf39-266x800.png, ruh-39-150x200.png';
$string = preg_replace('/('d{3}x'd{3})'./', '150x150.', $string);

-在此,我依靠在大小之后将有.作为文件扩展名分隔符。如果不是这样,您可能需要将其从替换条件中删除。

使用 preg_replace,您可以像这样实现您想要的:

$pattern = '/'d+x'd+('.png)/i';
$replace = '150x150${1}';
$newStr  = preg_replace($pattern, $replace, $initialStr);

另请参阅此简短演示

简短解释

RegEx-pattern:
                       /'d+x'd+('.png)/i
                        '_/V'_/'_____/ V
       _________         | | |    |    |   ________________
      |Match one|________| | |    |    |__|Make the search |
      |or more  |    ______| |    |___    |case-insensitive|
      |digits   |   |        |        |
             _______|_   ____|____   _|_______________
            |Match the| |Match one| |Match the string |
            |character| |or more  | |'.png' and create|
            |'x'      | |digits   | |a backreference  |
Replacement string:
                     150x150${1}
                     '_____/'__/
     ________________   |    |   ________________________
    |Replace with the|__|    |__|...followed by the 1st  |
    |string '150x150'|          |captured backreference  |
                                |(e.g.: ".png" or ".PNG")|