How to get substring from string with variable character length in php?

I have some data in the format

C222 = 50
C1234P687 = 'some text'
C123YYY = 'text'
C444 = 89
C345 = 3
C122P687 = 'some text'
C122YYY = 'text'
....
....

so basically 3 different shapes

  • "C" number = value, example - C444 = 89
  • "C" number "P" number = value, example - C123P687 = 'some text'
  • "C" number "YYY" = value

Only a number has a variable length on the left side of the sign (=). Values ​​vary.

I want to save data in db as

INSERT INTO datatable 
    c_id = "number after C"
    p_id = "number after P" // if it exists for a line of data
    value = 'value'
    yyy = 'value'

Any ideas on how to get these numbers?

thank

+3
source share
3 answers

PHP. , , - preg_match_all ( PREG_SET_ORDER), , , , 5 .

(C[\d]+)(P[\d]+)?(YYY)? = (.+)

.

"C".

"P", , .

"YYY", , .

.

, C P :

C([\d]+)(?:P([\d]+))?(YYY)? = (.+)

+5

, , - file_get_contents fopen.

.

http://php.net/manual/en/function.preg-match-all.php

# UPDATE REG EX UPDATED
preg_match_all("|C([\d]+)(?:P([\d]+))?(YYY)? = (.+)|", $yourDataLine, $out, PREG_SET_ORDER);

$out[0] = TESTED STRING e.g. C123 = 456;    
$out[1] = C;
$out[2] = P;
$out[3] = YYY;
$out[4] = VALUE;

reg :

+3

Solution without using regular expressions:

<?php

$s="C23YYY = 'hello world'";

$p1=explode('=',$s);

$left=trim($p1[0]);
$right=trim($p1[1]);

$value=$right;

if(substr($left,-3)!='YYY'){
    $pos=strpos($left,'P');
    if($pos!==false){
        $c_id=substr($left,1,$pos-1);
        $p_id=substr($left,1+$pos-strlen($left));
    }else{
        $c_id=substr($left,1-strlen($left));
    }
}else{
    $c_id=substr($left,1,strlen($left)-4);
    $yyy='YYY';
}

print("c_id = $c_id <br/>");
print("p_id = $p_id <br/>");
print("value = $value <br/>");
print("yyy = $yyy <br/>");

?>
+1
source

Source: https://habr.com/ru/post/1740430/


All Articles