There are lines

Example

910786584_w269_h230_40_2.jpg 

I need to replace _w269_h230_ with _w2000_h2000_

The problem is that each image has different sizes _w269_h230_, but the characters are always the same. How to properly hook and replace numbers

    2 answers 2

    You can conjure with preg_replace or just use explode-implode as an example

      <?php $string = '910786584_w269_h230_40_2.jpg'; $list = explode( '_', $string ); $list[ 1 ] = 'w2000'; $list[ 2 ] = 'h2000'; $result = implode( '_', $list ); print_r( $result ); ?> 

      Another option in the collection of answers. You can optimize the pattern, and use the hooks:

       $str = '910786584_w269_h230_40_2.jpg'; $patt = '~_([wh])\d+~'; $repl = '_${1}2000'; echo preg_replace($patt, $repl, $str); 

      If you need to substitute the values ​​separately, then you can divide one pattern into two (each for a specific match) :

       $str = '910786584_w269_h230_40_2.jpg'; $patt = ['~_w\d+~', '~_h\d+~']; $repl = ['_w2000', '_h2000']; echo preg_replace($patt, $repl, $str); 
      • It seems to me that the replacement of such a 910786584_w269_40_2.jpg not part of the plans - teran
      • @teran and how did you achieve this behavior? ) - Edward