1

I want to get the string between "yes""yes"

eg.

yes1231yesyes4567yes

output:

1231,4567

How to do it in php? may be there are 1 more output '' between yesyes right?

Darren
  • 13,050
  • 4
  • 41
  • 79
SFY
  • 61
  • 7

2 Answers2

4

In this particular example, you could use preg_match_all() with a regex to capture digits between "yes" and "yes":

preg_match_all("/yes(\d+)yes/", $your_string, $output_array);

print_r($output_array[1]);

// Array
// (
//     [0] => 1231
//     [1] => 4567
// )

And to achieve your desired output:

echo implode(',', $output_array[1]); // 1231,4567

Edit: side reference, if you need a looser match that will simply match all sets of numbers in a string e.g. in your comment 9yes123yes12, use the regex: (\d+) and it will match 9, 123 and 12.

scrowler
  • 24,273
  • 9
  • 60
  • 92
  • `\d+` means "match any number (digit) that occurs at least once". *edit* it's the same as `[0-9]+` – scrowler Jul 18 '14 at 02:41
  • thank , how about if i want to get the number of the string "we123a" is it preg_match_all("/we(\d+)a/", $your_string, $output_array); – SFY Jul 18 '14 at 02:47
  • Yes. This all totally depends on your application though, there is likely to be a better solution. If all you want is the numbers, just use `/(\d+)/` as the regex assuming they have anything other than numbers on either side of them (or the start or end of the string). – scrowler Jul 18 '14 at 02:49
  • `preg_match_all()`* - you must be doing something else incorrectly: http://www.phpliveregex.com/p/61P – scrowler Jul 18 '14 at 03:09
  • oh yes~ i put "/a" instead of "a/"......sorry that i wasted your time. 1 more thing i want to know why the array[0] is we123a , but not 123 – SFY Jul 18 '14 at 03:18
  • @SuenFalendo no worries. [Have a read through the PHP manual](http://php.net/manual/en/function.preg-match-all.php) - it's your best friend. The default "flags" setting for `preg_match_all()` is `$matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern` – scrowler Jul 18 '14 at 03:31
0

Good Evening,

If you are referring to extracting the digits (as shown in your example) then you can achieve this by referencing the response of Christopher who answered a very similar question on this topic:

PHP code to remove everything but numbers

However, on the other hand, if you are looking to extract all instances of the word "yes" from the string, I would recommend using the str_replace method supplied by PHP.

Here is an example that would get you started;

str_replace("yes", "", "yes I do like cream on my eggs");

I trust that this information is of use.

Community
  • 1
  • 1