fork(3) download
  1. <?php
  2. $regex = '~{[^}]+}|"Tarzan\d+"|(Tarzan\d+)~';
  3. $subject = 'Jane" "Tarzan12" Tarzan11@Tarzan22 {4 Tarzan34}';
  4. $count = preg_match_all($regex, $subject, $m);
  5.  
  6. // build array of non-empty Group 1 captures
  7. $matches=array_filter($m[1]);
  8.  
  9. ///////// The six main tasks we're likely to have ////////
  10.  
  11. // Task 1: Is there a match?
  12. echo "*** Is there a Match? ***<br />\n";
  13. if(empty($matches)) echo "No<br />\n";
  14. else echo "Yes<br />\n";
  15.  
  16. // Task 2: How many matches are there?
  17. echo "\n<br />*** Number of Matches ***<br />\n";
  18. echo count($matches)."<br />\n";
  19.  
  20. // Task 3: What is the first match?
  21. echo "\n<br />*** First Match ***<br />\n";
  22. if(!empty($matches)) echo array_values($matches)[0]."<br />\n";
  23.  
  24. // Task 4: What are all the matches?
  25. echo "\n<br />*** Matches ***<br />\n";
  26. if(!empty($matches)) {
  27. foreach ($matches as $match) echo $match."<br />\n";
  28. }
  29.  
  30. // Task 5: Replace the matches
  31. $regex,
  32. // in the callback function, if Group 1 is empty,
  33. // set the replacement to the whole match,
  34. // i.e. don't replace
  35. function($m) { if(empty($m[1])) return $m[0];
  36. else return "Superman";},
  37. $subject);
  38. echo "\n<br />*** Replacements ***<br />\n";
  39. echo $replaced."<br />\n";
  40.  
  41. // Task 6: Split
  42. // Start by replacing by something distinctive,
  43. // as in Step 5. Then split.
  44. $splits = explode("Superman",$replaced);
  45. echo "\n<br />*** Splits ***<br />\n";
  46. echo "<pre>"; print_r($splits); echo "</pre>";
  47.  
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
*** Is there a Match? ***<br />
Yes<br />

<br />*** Number of Matches ***<br />
2<br />

<br />*** First Match ***<br />
Tarzan11<br />

<br />*** Matches ***<br />
Tarzan11<br />
Tarzan22<br />

<br />*** Replacements ***<br />
Jane" "Tarzan12" Superman@Superman {4 Tarzan34}<br />

<br />*** Splits ***<br />
<pre>Array
(
    [0] => Jane" "Tarzan12" 
    [1] => @
    [2] =>  {4 Tarzan34}
)
</pre>