Remove Square Brackets and keep text depending on context

GenesisBits :

I have a string as so:

[[EARTH]] [[Machine]] [[Monster Card|monsters]]
If this card is [[Link Summon]]ed: You can [[Add a card|add]] 1 "[[Ancient Gear]]" monster or 1 "[[Geartown]]" from your [[Main Deck|Deck]] to your [[hand]]. You can [[target]] 1 [[Spell Card|Spell]]/[[Trap Card|Trap]] you [[control]] and 1 [[face-up]] monster your opponent controls; [[destroy]] that card you control, and if you do, change that opponents monsters [[ATK]]/[[DEF]] to 0 until the end of this [[turn]]. You can only use each [[effect]] of "Ancient Gear Ballista" [[once per turn]].

I'm using the following piece of code to remove all square brackets:

$stringout = str_replace(array('[[',']]'),'',$stringout);

However, when the brackets contain | character, I need to keep only the text after this character.

So from this:

[[Monster Card|monsters]]

To this:

monsters

I tried this:

$stringout = str_replace(array('[[|',']]'),'',$stringout);
CBroe :

Really more a job for preg_replace and regular expressions, than simple string replacement.

$result = preg_replace('#\[\[(?:[^\]]*\|)?([^\]]*)\]\]#', '$1', $input);

(?:[^\]]*\|)? is a non-capturing group, that allows for an optional ...| part. Optional, so that $1 will always refer to the second part, which would either be the rest after that, or the full content between [[…]], if there was no |.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=302527&siteId=1