2013-10-17 40 views
0

我有一個字符串,其中包含許多具有各種圖像大小的wordpress圖像名稱。例如:在PHP中替換所有出現的字符串中的文本模式

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

我需要做的就是更換所有的圖像尺寸在這樣的一個字符串「150×150」字符串。該字符串可能具有數百個具有不同大小的不同文件名。 到目前爲止,所有尺寸的格式都是dddxddd - 3個數字由'x'跟着另外3個數字。我不認爲我會有4位數的寬度或高度。 總是在.png擴展名之前。 所以處理上述字符串後,它應該成爲這樣的:

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

任何幫助將不勝感激。

+0

強制性 「你嘗試過什麼?」 – pduersteler

+0

我試圖在每個級別使用不同大小(針)的嵌套str_replace()函數,但這不是一個優雅的解決方案。如果我只有3或4種不同的尺寸需要替換,它可以正常工作,但將來我會有很多不同的尺寸,並且爲每種尺寸嵌套越來越多的str_replace是非常討厭的。所以我需要找到更好的更優雅的方式。 –

+2

你想要['preg_replace'](http://uk1.php.net/preg_replace),在正則表達式中你可以使用一些'+ d'和一些括號'() ' – SmokeyPHP

回答

3
$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' 
); 
+0

錯誤dans「$ sizex $大小」。 。 $ sizex將是一個變量。 – jacouh

+0

@jacouh喲,謝謝,還沒有檢查。 –

+0

所以d {3,4}是指任何長度爲3或4位數的數字,對嗎?另外,\ \做什麼?它就像一個逃生角色? –

2

這將是這樣的:

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

-in這個我依靠的是規模後會有.爲文件擴展名的分隔符。如果不是這樣,你可能想從更換條件中刪除它。

2

使用preg_replace,你可以達到你想要的東西是這樣的:

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

還參見本short demo

簡短解釋

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")| 
+0

+1爲ASCII藝術 – pduersteler

相關問題