Moin Uddin
Moin Uddin

Reputation: 157

php regex to get all int or decimal from pattern

Purpose of my code to get all take profit which has int or decimal value. writing pattern of Takeprofit will not same.

Problem:

  1. i want $m[3][4] or $m[4][4] as 1.0870 but i got only 0870. i am getting this result when number starts from 1.xxxx. They are conflicting. I can not solve
  2. TP-----1.0870 and TP=1.0870 are not detected

My Code:

<?php
$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-----1.0870 TP=1.0870 TP1=1.0870 TP Open';

$p = '#\b(TP1|TP 1|TP2|TP 2|TP3|TP 3|TAKE PROFIT 1|TAKE PROFIT 2|TAKE PROFIT 3|TAKEPROFIT 1|TAKEPROFIT 2|TAKEPROFIT 3|TAKEPROFIT\|TP)(.*?)(\bOpen\b|\b(\d+(?:\.\d+)?)\b)\b#i';

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

Result of $m:

Array
(
    [0] => Array
        (
            [0] => TP1 1.0870
            [1] => TP 1 1.0870
            [2] => TP 2 1.0870
            [3] => Take profit 1 1.0870
            [4] => TP 1.0870
            [5] => TP1=1.0870
        )

    [1] => Array
        (
            [0] => TP1
            [1] => TP 1
            [2] => TP 2
            [3] => Take profit 1
            [4] => TP 1
            [5] => TP1
        )

    [2] => Array
        (
            [0] =>  
            [1] =>  
            [2] =>  
            [3] =>  
            [4] => .
            [5] => =
        )

    [3] => Array
        (
            [0] => 1.0870
            [1] => 1.0870
            [2] => 1.0870
            [3] => 1.0870
            [4] => 0870
            [5] => 1.0870
        )

    [4] => Array
        (
            [0] => 1.0870
            [1] => 1.0870
            [2] => 1.0870
            [3] => 1.0870
            [4] => 0870
            [5] => 1.0870
        )

)

Upvotes: 2

Views: 58

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627335

You may use

'~\b(TAKE ?PROFIT ?(?:[1-3]|\|TP)|TP ?(?:[1-3](?!\.\d))?)\b(.*?)\b(Open|(\d+(?:\.\d+)?))\b~i'

See the regex demo

Details

  • \b - word boundary
  • (TAKE ?PROFIT ?(?:[1-3]|\|TP)|TP ?(?:[1-3](?!\.\d))?) - Group 1: TAKE, an optional space, PROFIT, an optional space, then a digit from 1 to 3 or |TP substring, or TP with an optional space after it that is optionally followed with 1, 2 or 3 that are not followed with . and a digit
  • \b - word boundary
  • (.*?) - Group 2: any 0+ chars other than line break chars as few as possible
  • \b - word boundary
  • (Open|(\d+(?:\.\d+)?)) - Group 3: Open or Group 4: 1+ digits followed with an optional sequence of . and 1+ digits
  • \b - word boundary.

Upvotes: 1

Related Questions