2012-02-23 15 views
14
$string = ":abc and :def have apples."; 
$replacements = array('Mary', 'Jane'); 

हो जाना चाहिए:preg_replace

Mary and Jane have apples. 

अभी मैं इस तरह यह कर रहा हूँ:

preg_match_all('/:(\w+)/', $string, $matches); 

foreach($matches[0] as $index => $match) 
    $string = str_replace($match, $replacements[$index], $string); 

मैं एक ही समय में यह कर सकता, preg_replace की तरह कुछ का उपयोग कर ?

+1

[यह] (http://codepad.org/KfP3g02m) कैसे आप एक साहचर्य सरणी के साथ यह कर सकते हैं है। – Teneff

उत्तर

10

आप एक कॉलबैक कि आपके प्रतिस्थापन एक के बाद एक की खपत के साथ preg_replace_callback इस्तेमाल कर सकते हैं: एक के लिए

Mary and Jane have apples. 
+0

ई संशोधक को PHP v.5.5 – Kareem

+1

@ करिम के रूप में घटा दिया गया है: ठीक है, इसे उत्तर से हटा दिया है। सूचक के लिए धन्यवाद। – hakre

8
$string = ":abc and :def have apples."; 
$replacements = array('Mary', 'Jane'); 

echo preg_replace("/:\\w+/e", 'array_shift($replacements)', $string); 

आउटपुट multipl

$words=array("_saudation_"=>"Hello", "_animal_"=>"cat", "_animal_sound_"=>"MEooow"); 
    $source=" _saudation_! My Animal is a _animal_ and it says _animal_sound_ ... _animal_sound_ , _no_match_"; 


    function translate_arrays($source,$words){ 
    return (preg_replace_callback("/\b_(\w*)_\b/u", function($match) use ($words) { if(isset($words[$match[0]])){ return ($words[$match[0]]); }else{ return($match[0]); } }, $source)); 
    } 


    echo translate_arrays($source,$words); 
    //returns: Hello! My Animal is a cat and it says MEooow ... MEooow , _no_match_ 

* सूचना है, thats हालांकि "_no_match_" अनुवाद का अभाव है, यह regex के दौरान की भरपाई कर देंगे, लेकिन उसके प्रमुख की रक्षा: ई और साहचर्य कुंजी द्वारा पूर्ण सरणी प्रतिस्थापन आप इस का उपयोग कर सकते अपने regex पैटर्न मिलान करने के लिए। और चाबियाँ कई बार दोहरा सकती हैं।

+0

यह एचएचवीएम पर किसी भी कामकाज पर काम नहीं करेगा? – Mario

3

:

$string = ":abc and :def have apples."; 
$replacements = array('Mary', 'Jane'); 
echo preg_replace_callback('/:\w+/', function($matches) use (&$replacements) { 
    return array_shift($replacements); 
}, $string); 

आउटपुट:

Mary and Jane have apples. 
+0

मैं यूटीएफ -8 तारों का समर्थन करने के लिए रेगेक्स में "यू" संशोधक जोड़ने की सलाह देता हूं: '/ \ b _ (\ w *) _ \ b/u'। बीटीडब्ल्यू, उपरोक्त कोड में सिंटैक्स त्रुटि है, और अंत में अतिरिक्त कोष्ठक है। – nikoskip

+0

कोई अतिरिक्त कंस्ट्रैसिस समस्या नहीं दिखता है, मैंने कोड सत्यापित किया है और ठीक चल रहा है। मैंने यूटीएफ -8 को जोड़ा। धन्यवाद – Miguel

6

यहाँ इस

$to_replace = array(':abc', ':def', ':ghi'); 
$replace_with = array('Marry', 'Jane', 'Bob'); 

$string = ":abc and :def have apples, but :ghi doesn't"; 

$string = strtr($string, array_combine($to_replace, $replace_with)); 
echo $string; 

प्रयास करें परिणाम है: http://sandbox.onlinephpfunctions.com/code/7a4c5b00f68ec40fdb35ce189d26446e3a2501c2

+1

यह सबसे तेज़ समाधान है क्योंकि यह regex का उपयोग नहीं करता है – Drakes

संबंधित मुद्दे