[英]How replace chars between two strings
I have text like: 我有这样的文字:
$text = 'number="1" body="Are you "special" man?" name="man" code="1"
number="2" body="Hi said "HaHaHa""?" name="man" code="2"'
I working on it but without any success. 我正在努力,但没有成功。 I need to replace all
"
with #
in body section. Can somebody help me with this? 我需要在正文部分将所有
"
替换为#
。有人可以帮我吗?
So result should be: 所以结果应该是:
$text = 'number="1" body="Are you #special# man?" name="man" code="1"
number="2" body="Hi said #HaHaHa#?" name="man" code="2"'
Complex solution with preg_replace
and preg_replace_callback
functions: 使用
preg_replace
和preg_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);
The output: 输出:
number="1" body="Are you #special# man?" name="man" code="1"
number="2" body="Hi said #HaHaHa#?" name="man" code="2"
I was going along the same lines as RomanPerekhrest : 我和RomanPerekhrest遵循相同的思路 :
preg_match_all('/body="(.*?)" /', $text, $matches);
foreach($matches[1] as $find) {
$text = str_replace($find, str_replace('"', '#', $find), $text);
}
Get all of the body="something"
and replace any "
that are inside the ""
. Replace the original body="something"
with the new one. 获取所有
body="something"
并替换"
内的所有""
,将原来的body="something"
替换为新的body="something"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.