![](/img/trans.png)
[英]I want to replace all occurences of a string which are not enclosed within < … >
[英]Replace all spaces which are enclosed within braces
我想要做的是找到括在括号中的所有空格,然后用另一个字符替换它们。
就像是:
{The quick brown} fox jumps {over the lazy} dog
改为:
{The*quick*brown} fox jumps {over*the*lazy} dog
我已经在网上搜索了,但这只是我到目前为止所得到的,而且它似乎非常接近我真正想要的东西。
preg_replace('/(?<={)[^}]+(?=})/','*',$string);
上面代码的问题在于它取代了所有内容:
{*} fox jumps {*} dog
我正在研究正则表达式教程,以弄清楚我应该如何修改上面的代码只是替换空格但无济于事。 任何输入都将受到高度赞赏。
谢谢。
假设所有大括号都已正确嵌套,并且没有嵌套大括号,您可以使用前瞻断言来执行此操作:
$result = preg_replace('/ (?=[^{}]*\})/', '*', $subject);
仅当下一个括号是右括号时,才匹配并替换空格:
(?= # Assert that the following regex can be matched here:
[^{}]* # - Any number of characters except braces
\} # - A closing brace
) # End of lookahead
我对你的评论作出反应,你不想使用正则表达式,只是字符串操作。 那没关系,但为什么你写下你正在寻找一个正则表达式?
解决方案没有正则表达式:
<?php
$str = "{The quick brown} fox jumps {over the lazy} dog";
for($i = 0, $b = false, $len = strlen($str); $i < $len; $i++)
{
switch($str[$i])
{
case '{': $b = true; continue;
case '}': $b = false; continue;
default:
if($b && $str[$i] == ' ')
$str[$i] = '*';
}
}
print $str;
?>
这个怎么样:
$a = '{The quick brown} fox jumps {over the lazy} dog';
$b = preg_replace_callback('/\{[^}]+\}/sim', function($m) {
return str_replace(' ', '*', $m[0]);
}, $a);
var_dump($b); // output: string(47) "{The*quick*brown} fox jumps {over*the*lazy} dog"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.