![](/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.