2017-10-12 119 views
2

我有這樣的文字:如何兩個字符串之間替換字符

$text = 'number="1" body="Are you "special" man?" name="man" code="1" 
     number="2" body="Hi said "HaHaHa""?" name="man" code="2"' 

我的工作就可以了,但沒有成功。我需要在身體部分替換全部"#。有人可以幫助我嗎?

所以結果應該是:

$text = 'number="1" body="Are you #special# man?" name="man" code="1" 
     number="2" body="Hi said #HaHaHa#?" name="man" code="2"' 
+0

如果你這樣做,你會遇到問題的字符串! –

+0

它可以替換爲#或者其他的 – user3345547

+0

所以你想把''「HaHaHa」'改成'#HaHaHa#'? –

回答

2

preg_replacepreg_replace_callback功能複雜的解決方案:

$text = 'number="1" body="Are you "special" man?" name="man" code="1" 
     number="2" body="Hi said "HaHaHa""?" name="man" code="2"'; 

$text = preg_replace_callback('/(body=")(.*)(?=" name)/', function($m) { 
    return $m[1] . preg_replace('/"+/', '#', $m[2]); 
}, $text); 

print_r($text); 

輸出:

number="1" body="Are you #special# man?" name="man" code="1" 
     number="2" body="Hi said #HaHaHa#?" name="man" code="2" 
1

我正沿着相同的路線爲RomanPerekhrest去:

preg_match_all('/body="(.*?)" /', $text, $matches); 

foreach($matches[1] as $find) { 
    $text = str_replace($find, str_replace('"', '#', $find), $text); 
} 

獲取所有的body="something"和替換是""內的任何"。用新的替換原來的body="something"

相關問題