[英]How to extract a substring from a string in PHP until it reaches a certain character?
[英]how to retrieve substring from string having variable length of character in php?
我有一些格式的數據
C222 = 50
C1234P687 = 'some text'
C123YYY = 'text'
C444 = 89
C345 = 3
C122P687 = 'some text'
C122YYY = 'text'
....
....
基本上有3種不同的形式
只有數字在(=)符號的左側具有可變長度。 價值各不相同
我想將數據存儲在db中
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'
有任何想法如何檢索這些數字?
謝謝
在PHP中使用正則表達式。 以下正則表達式模式將匹配您提供的所有情況 - 將它與preg_match_all (傳入數組和PREG_SET_ORDER
)一起使用,然后傳入的數組將包含每行數據的數組,並且每行的數組將包含5元素。
(C[\d]+)(P[\d]+)?(YYY)? = (.+)
數組的第一個元素將包含已測試的完整字符串。
數組的第二個元素將包含“C”數字。
如果存在,則數組的第三個元素將包含“P”數字,否則它將為空白。
如果存在,數組的第四個元素將包含“YYY”,否則它將為空白。
數組的第五個元素將包含該值。
在回應之前的評論時,以下正則表達式是上述的修改版本,但不包括匹配值中的C
和P
:
C([\\d]+)(?:P([\\d]+))?(YYY)? = (.+)
我假設數據是從文件讀入的,所以使用像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表達感謝:Andy Shellam
不使用正則表達式的解決方案:
<?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/>");
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.