Php 如何从字符串中用大写字母查找(并替换)单词? $string=“WORD是第一个,HEJOU是第二个,BOOM是第三个”; $sring=str_replce('???','???',$string); echo$string;//

Php 如何从字符串中用大写字母查找(并替换)单词? $string=“WORD是第一个,HEJOU是第二个,BOOM是第三个”; $sring=str_replce('???','???',$string); echo$string;//,php,string,replace,Php,String,Replace,这个例子本身就说明了这一点。我想选择所有大写字母的单词(不是以大写字母开头的单词)并替换为前面的单词。有什么想法吗?使用正则表达式 使用正则表达式 str\u replace只需将特定字符串替换为其他特定字符串即可。您可以使用preg\u replace $string = "WORD is the first HEJOU is the Second BOOM is the Third"; $sring = str_replce('???', '???<br>', $string);

这个例子本身就说明了这一点。我想选择所有大写字母的单词(不是以大写字母开头的单词)并替换为前面的单词。有什么想法吗?

使用正则表达式


使用正则表达式


str\u replace
只需将特定字符串替换为其他特定字符串即可。您可以使用
preg\u replace

$string = "WORD is the first HEJOU is the Second BOOM is the Third";
$sring = str_replce('???', '???<br>', $string);
echo $string; // <br>WORD is the first <br>HEJOU is the Second <br>BOOM is the Third
打印预替换(“~\b[A-Z]+\b~”、“
\\0”、$string);
str\u replace
只需将特定字符串替换为其他特定字符串即可。您可以使用
preg\u replace

$string = "WORD is the first HEJOU is the Second BOOM is the Third";
$sring = str_replce('???', '???<br>', $string);
echo $string; // <br>WORD is the first <br>HEJOU is the Second <br>BOOM is the Third
打印预替换(“~\b[A-Z]+\b~”、“
\\0”、$string);
然后,在替换中,

\b - Match a word boundary, zero width
[A-Z]+ - Match any combination of capital letters 
\b - Match another word boundary
([A-Z]+) - Capture the word for use in the replacement
然后,在替换中,

\b - Match a word boundary, zero width
[A-Z]+ - Match any combination of capital letters 
\b - Match another word boundary
([A-Z]+) - Capture the word for use in the replacement

我想您的意思是替换为对
\\1
的反向引用,而不是
\\0
,它与整个输入匹配。@sberry您可以在我的regexp中看到no\1\\0是完全匹配的regexp。我想您的意思是将其替换为对
\\1
的反向引用,而不是
\\0
,它与整个输入匹配。@sberry您可以在我的regexp中看到no\1\\0是完全匹配的regexp。它工作,它只是一个分隔符。“#”可以替换为另一个字符。/这很常见。我似乎总是用#它只是一个分隔符。“#”可以替换为另一个字符。/这很常见。我似乎总是用#
\\1, replace with the captured group.