fork(2) download
  1. <?php
  2. $regex = '~(?:{[^}]+}|"Tarzan\d+")(*SKIP)(*F)|Tarzan\d+~';
  3. $subject = 'Jane" "Tarzan12" Tarzan11@Tarzan22 {4 Tarzan34}';
  4. $count = preg_match_all($regex, $subject, $matches);
  5. // $matches[0] contains the matches, if any
  6.  
  7. ///////// The six main tasks we're likely to have ////////
  8.  
  9. // Task 1: Is there a match?
  10. echo "*** Is there a Match? ***<br />\n";
  11. if($count) echo "Yes<br />\n";
  12. else echo "No<br />\n";
  13.  
  14. // Task 2: How many matches are there?
  15. echo "\n<br />*** Number of Matches ***<br />\n";
  16. if($count) echo count($matches[0])."<br />\n";
  17. else echo "0<br />\n";
  18.  
  19. // Task 3: What is the first match?
  20. echo "\n<br />*** First Match ***<br />\n";
  21. if($count) echo $matches[0][0]."<br />\n";
  22.  
  23. // Task 4: What are all the matches?
  24. echo "\n<br />*** Matches ***<br />\n";
  25. if($count) {
  26. foreach ($matches[0] as $match) echo $match."<br />\n";
  27. }
  28.  
  29. // Task 5: Replace the matches
  30. $replaced = preg_replace($regex,"Superman",$subject);
  31. echo "\n<br />*** Replacements ***<br />\n";
  32. echo $replaced."<br />\n";
  33.  
  34. // Task 6: Split
  35. $splits = preg_split($regex,$subject);
  36. echo "\n<br />*** Splits ***<br />\n";
  37. echo "<pre>"; print_r($splits); echo "</pre>";
  38. ?>
Success #stdin #stdout 0.01s 20520KB
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>