[英]PHP regex find and replace with new string
我有一個字符串,其中包含:
[quote name="username" url="/t/44223/topics-name#post_734738"]
我想編寫一個php正則表達式,它將查找該字符串的所有出現並找到帖子號(例如734738),然后將整個內容替換為:
[quote=username;new post number based on 734738]
要求:
請幫幫我。 謝謝。
如果有人需要,這是最終的答案:)
$string = '[quote name="user343I_nsdfdame" url="/t/44223/topics-name#post_734738"]What is your name?[/quote][quote name="username" url="/t/45454/topics-name#post_767676"]Test string[/quote]The quick brown fox....';
if(preg_match_all("/\[quote name=\"([^\"]*)\" url=\"\/t\/[^#]*#post_([0-9]*)\"\]/", $string, $matches)) {
foreach ($matches[0] as $match) {
if(preg_match("/\[quote name=\"([^\"]*)\" url=\"\/t\/[^#]*#post_([0-9]*)\"\]/",$match, $reg)) {
$new = "[quote=".$reg[1].";".$reg[2]."]"; // I have changed $reg[2] according to my need.
$string = str_replace($match, $new, $string);
}
}
}
echo $string;
輸出:
[quote=user343I_nsdfdame;734738]What is your name?[/quote][quote=username;767676]Test string[/quote]The quick brown fox....
這樣做:
$string = '[quote name="username" url="/t/44223/topics-name#post_734738"]';
$new = "";
if(preg_match("/\[quote name=\"([^\"]*)\" url=\"\/t\/[^#]*#post_([0-9]*)\"\]/",$string,$reg)) {
$new = "[quote=".$reg[1].";new post number based on ".$reg[2]."]";
}
echo $new;
輸出為:
[quote=username;new post number based on 734738]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.