PHP:如何以给定格式转换这句话

标签 php regex code-snippets

"[5|five] [Tips|Suggestions] for an Unforgettable Trip|Five suggestions for a un-regret able Trip|[5|five] [tips|suggestions] for an [amazing|incredible] Trip|Five [tips|suggestions] for an astonishing Trip"

"[5|five] [Tips|Suggestions] for an Unforgettable Trip~Five suggestions for a un-regret able Trip~[5|five] [tips|suggestions] for an [amazing|incredible] Trip~Five [tips|suggestions] for an astonishing Trip"

我可以使用 str_replace("|", "~", $code) 但问题是我不想将 "|" 转换为 "~" 如果它在 "[ ]" 之间。

最佳答案

for($i=0,$s=strlen($str),$c=0;$i<$s;++$i){
    if($str[$i]=='[')++$c;
    elseif($str[$i]==']')--$c;
    elseif(!$c && $str[$i]=='|')$str[$i]='~';
}

关于PHP:如何以给定格式转换这句话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6677838/

相关文章:

php - Route::resource 和 Route::controller 等同于流明?

php - 如何在 laravel 5.4 中使用 style.css 文件?

php - when in 从句与 mysql pdo

regex - 一个或两个字母后跟 3-4 个数字

linux - 在 Qt Creator 中,Ubuntu 中的用户片段在哪里?

php - 区分盗链与现场用户

regex - Sed 用文件内容替换模式

javascript - JS替换Word后面的反斜杠

c# - C# 的 VS 2008 VB 片段

sass - SublimeText是否不允许摘要中包含$ variables?