You've said in your question "how to get everything before and after a certain word". So this will get everything. Replace the instances of .*
with eg \d*
to get eg numberic digits either side.
The following will return 0 if no match found at all, or >0 if matches found.
preg_match_all('/^(.*)times(.*)$/', $yourStringToSearch, $arr, PREG_PATTERN_ORDER);
If matches found, $arr
will be populated.
So eg if "times" is found, but without pre/post text, then it'll return 1, and $arr[0]
will contain only "times".
So for example, if $yourStringToSearch
contains "5 times 8", then $arr
will be populated as follows (where $arr[0]
is the entire match, $arr[1]
is the pre-text, and $arr[2]
is the post-text).
Array
(
[0] => Array
(
[0] => 5 times 8
)
[1] => Array
(
[0] => 5
)
[2] => Array
(
[0] => 8
)
)
But, be careful because if $yourStringToSearch = "5 _times_ -times- 8"
it'll return:
Array
(
[0] => Array
(
[0] => 5 _times_ -times- 8
)
[1] => Array
(
[0] => 5 _times_ -
)
[2] => Array
(
[0] => - 8
)
)
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.
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:
preg_match_all('/^(.*) times (.*)$/', $yourStringToSearch, $arr, PREG_PATTERN_ORDER);
preg_match_all('/^(.* )times( .*)$/', $yourStringToSearch, $arr, PREG_PATTERN_ORDER);