简体   繁体   中英

php regex to get a string pattern

I want to get all take profit value from a raw text. however writing pattern is not same.

I get all values fine which i want except for 20/30/50. for that value i get only 20.

I want whole word as 20/30/50

$s = 'SS 1.0140 SL 1.0670 TP1 1.0870 TP 1 1.0870 TP 2 1.0870 Takeprofit1 1.0870 Take profit 1 1.0870 TP 1.0870 TP 20/30/50 TP-----1.0870 TP=1.0870 TP1=1.0870 TP Open';

$p = '#\b(TAKE ?PROFIT ?(?:[1-3]|\|TP|at)|TP ?(?:[1-3](?!\.\d))?)\b(.*?)\b(Open|(\d+(?:\.\d+)?))\b#i';

preg_match_all($p , $s , $m);

result of $m[3] :

Array
(

    [3] => Array
        (

            [0] => 1.0870
            [1] => 1.0870
            [2] => 1.0870
            [3] => 1.0870
            [4] => 1.0870
            [5] => 1.0870
            [6] => 20
            [7] => 1.0870
            [8] => 1.0870
            [9] => 1.0870
            [10] => Open
        )
)

Add (?:/\\d+)* to your third capture group.

https://regex101.com/r/hsQ0xD/1/

This makes the repeating non-capturing group (substring) "slash then one or more numbers" optional.

Code: ( Demo )

$s = 'SS 1.0140 SL 1.0670 TP1 1.0870 TP 1 1.0870 TP 2 1.0870 Takeprofit1 1.0870 Take profit 1 1.0870 TP 1.0870 TP 20/30/50 TP-----1.0870 TP=1.0870 TP1=1.0870 TP Open';

$p = '#\b(TAKE ?PROFIT ?(?:[1-3]|\|TP|at)|TP ?(?:[1-3](?!\.\d))?)\b(.*?)\b(Open|(\d+(?:\.\d+)?(?:/\d+)*))\b#i';

preg_match_all($p , $s , $m);

var_export($m[3]);

Output:

array (
  0 => '1.0870',
  1 => '1.0870',
  2 => '1.0870',
  3 => '1.0870',
  4 => '1.0870',
  5 => '1.0870',
  6 => '20/30/50',
  7 => '1.0870',
  8 => '1.0870',
  9 => '1.0870',
  10 => 'Open',
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM