2

In PHP, I need to replace a fixed prefix and suffix surrounding a variable value.

The quotes around the value are stripped, except if the value is a string.

[blargh="5"]                  =>   <potato chips=#5#>
[blargh="97"]                 =>   <potato chips=#97#>
[blargh="StackOverflow"]      =>   <potato chips=#"StackOverflow"#>

I know that somehow, I can use preg_replace() to do this, but I do not know how.

DaveTheMinion
  • 664
  • 3
  • 22
  • 45

2 Answers2

3

Branch Reset: (?| ... )

The tricky part in your question is that for "StackOverflow" we include the quotes in the replacement, but for "87" we strip them. No fear, the branch reset feature handles that gracefully.

In the Regex Demo, see the substitutions at the bottom.

Sample PHP Code

$yourstring = '[blargh="5"] [blargh="97"] [blargh="StackOverflow"]';
$replaced = preg_replace('~\[blargh=(?|"(\d+)"|("[^"]*"))\]~',
                          '<potato chips=#\1#>', 
                          $yourstring);
echo $replaced;

Output

<potato chips=#5#> <potato chips=#97#> <potato chips=#"StackOverflow"#>

Our Search Regex:

\[blargh=(?|"(\d+)"|("[^"]*"))\]

Our Replacement String

<potato chips=#\1#>

Explanation

  • \[blargh= matches literal chars
  • In the branch reset (?| .... ), the groups all capture to Group 1
  • "(\d+)" captures digits inside quotes to Group 1 (but don't capture the quotes)
  • OR |
  • ("[^"]*") capture a complete "quoted string" to Group 1
  • \] matches the closing bracket
  • In the replacement, <potato chips=#\1#>, \1 is a back-reference to Group 1

Reference

zx81
  • 41,100
  • 9
  • 89
  • 105
  • Thanks. I added an edit to my question that has some code that I was using to test the method. I am having a problem with it. After running `preg_replace`, echoing the variable does not produce any result. – DaveTheMinion Jul 31 '14 at 04:41
  • I edited your test code, it runs perfectly. However if it does not show in your browser, it is because the output is a ``, so make sure you EITHER look at the html source in the brower (Ctrl/Cmd + U) OR `echo htmlentities($replaced);` – zx81 Jul 31 '14 at 04:50
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/58399/discussion-between-zx81-and-davidb). – zx81 Jul 31 '14 at 05:00
  • *slaps self in face* Of course it's not gonna show! I appologize for the stupidity in what I said. Viewing source shows it just fine. – DaveTheMinion Jul 31 '14 at 05:05
  • Common problem. I often test in a php console so this doesn't happen. :) Is it working now? – zx81 Jul 31 '14 at 05:07
  • How would I capture two separate groups? – DaveTheMinion Aug 01 '14 at 04:44
  • Separate groups: multiple parentheses, e.g. `(a+)b(c+)` captures some as to Group 1 and bs to Group 2, to which you can refer as `\1`, `\2` etc Please see [Capture Group Numbering & Naming: The Gory Details](http://www.rexegg.com/regex-capture.html) – zx81 Aug 01 '14 at 06:13
  • Okay. I need to split up the tag `[img=10x100]` where in this example, 10 is length and 100 is width. I've been messing with it for hours now with no success. – DaveTheMinion Aug 01 '14 at 17:22
  • David, use `\[img=(\d+)x(\d+)\]`, but for future needs please ask new questions as it's really hard to troubleshoot any new problems to extended questions in the comments. – zx81 Aug 01 '14 at 20:40
  • Okay, thanks for the help, and thanks for the advice. I hesitate to ask new questions because I am at risk of being question banned at the moment. – DaveTheMinion Aug 01 '14 at 20:55
2

You can use regular expression using a callback as well.

$text = '[blargh="5"] would convert, [blargh="97"] and [blargh="StackOverflow"]';

$text = preg_replace_callback('~\[blargh="([^"]*)"\]~', 
      function($m) {
         $which = is_numeric($m[1]) ? $m[1] : '"'.$m[1].'"';
         return '<potato chips=#' . $which . '#>';
      }, $text);

echo $text;

Output

<potato chips=#5#> would convert, <potato chips=#97#> and <potato chips=#"StackOverflow"#>
hwnd
  • 69,796
  • 4
  • 95
  • 132
  • I have absolutely no idea what a callback function is. – DaveTheMinion Jul 31 '14 at 04:46
  • +1 for callback. David, a callback function lets you build a complex replacement. For instance, within the callback function, you could if you wished talk to a database, retrieve data from Mars, and include it in your replacement—so it's very flexible. In this case, the anonymous function performs a test on the match, and, depending on whether it was a numeric value, returns one kind of replacement or another. It's a great technique to be aware of and you might want to use it at some later stage for your parser. – zx81 Jul 31 '14 at 05:47
  • @zx81 Oh. There are instances where I want whole pieces of HTML to vary based on certain conditions. Until now I have been using heredoc with variables that I set beforehand. This sounds much more efficient. – DaveTheMinion Jul 31 '14 at 16:27