Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You've said in your question "how to get <em>everything</em> before and after a certain word". So this will get <em>everything</em>. Replace the instances of <code>.*</code> with eg <code>\d*</code> to get eg numberic digits either side.</p> <p>The following will return 0 if no match found at all, or >0 if matches found. </p> <p><code>preg_match_all('/^(.*)times(.*)$/', $yourStringToSearch, $arr, PREG_PATTERN_ORDER);</code></p> <p>If matches found, <code>$arr</code> will be populated. </p> <p>So eg if "times" is found, but without pre/post text, then it'll return 1, and <code>$arr[0]</code> will contain only "times". </p> <p>So for example, if <code>$yourStringToSearch</code> contains "5 times 8", then <code>$arr</code> will be populated as follows (where <code>$arr[0]</code> is the entire match, <code>$arr[1]</code> is the pre-text, and <code>$arr[2]</code> is the post-text).</p> <pre><code>Array ( [0] =&gt; Array ( [0] =&gt; 5 times 8 ) [1] =&gt; Array ( [0] =&gt; 5 ) [2] =&gt; Array ( [0] =&gt; 8 ) ) </code></pre> <p>But, be careful because if <code>$yourStringToSearch = "5 _times_ -times- 8"</code> it'll return:</p> <pre><code>Array ( [0] =&gt; Array ( [0] =&gt; 5 _times_ -times- 8 ) [1] =&gt; Array ( [0] =&gt; 5 _times_ - ) [2] =&gt; Array ( [0] =&gt; - 8 ) ) </code></pre> <p>That is - you need to either specify what you want to happen in the case where your search string appears more than once in the target, or accept the "default" in this case where the first match on your search term is "the" match.</p> <p>If you need to ensure the search term is surrounded by spaces, then the following two will work. THe first assumes you don't want to "capture" the space, while the second will include the space in the captures:</p> <p><code>preg_match_all('/^(.*) times (.*)$/', $yourStringToSearch, $arr, PREG_PATTERN_ORDER);</code></p> <p><code>preg_match_all('/^(.* )times( .*)$/', $yourStringToSearch, $arr, PREG_PATTERN_ORDER);</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload