1

What I needed was either a str_replace or regex to replace the text between a set of parenthesis within a string where the parenthesis could occur more than once and the content of that text would be unknown.

There are several answers - some of which are marked as duplicates, yet none of them actually answer this simple question, so after searching for nearly an hour, and finding nothing, I decided to ask the question. And since I eventually figured it out using the preg_replace tool at functions-online, I figured I would post it and maybe someone else can come up with a better solution or possibly present a str_replace variant for php.

So here is what I came up with - that works - but please feel free to suggest better options.

//test string
$string = 'Fearless, Immunity (Cursed), Summoned (Spellcaster), Tactician, Tough/4';
$repVal = '(X)';

$count = null;
$returnValue = preg_replace('~\\([^\\)]*\\)~', $repVal, $string, -1, $count);
$returnValue = preg_replace('~(\\/)(\\d+)~', '/#', $string, -1, $count);

After running both preg_replace statements, the returned string will equal:

'Fearless, Immunity (X), Summoned (X), Tactician, Tough/#, Undead'

PS: I also needed to replace the /4 or any other /x strings with /#, so I included that statement as well.

Obewan
  • 121
  • 6
  • This question has been answered *many* times before, so I don't know why you're claiming all other posts are incorrect.... – Tom Lord May 19 '17 at 14:13
  • I don't know why this is marked as a duplicate when the supposed duplicate asks how to remove the text and while it has a similar expression - it is different. Additionally, this question ASKS for improvements which might include other options such as str_replace... but whatever. – Obewan May 19 '17 at 14:15
  • Tom Lord, I tried some of the other code/expressions and none that I found did the task that was required. Maybe I missed it, but after getting frustrated and finally figuring something out that worked, I decided to post the answer AND ask for improvements because I am sure there is a better way to do it... but again, whatever. – Obewan May 19 '17 at 14:18
  • Try using this http://php.net/manual/en/function.substr-replace.php – nomistic May 19 '17 at 14:23
  • If there are a dozen other questions for *almost the same thing*, is it really necessary to post yet-another question with your slight variations? Is someone googling this question going to find your answer helpful where a dozen other aren't? A "duplicate" question won't necessarily be **identical**; but you could easily have gotten a similar answer to this question from the linked one. – Tom Lord May 19 '17 at 15:55

0 Answers0