Selecting a part of a string

…衆ロ難τιáo~ 提交于 2020-01-04 06:22:42

问题


I have a string stored in variable say

$input = 999 success: id:10.123/AVC13231 | ark:/asf4523/2425fsaf

I want to select only a part of a string "10.123/AVC13231"

say i want to achieve this:

$output = 10.123/XXXXXXXX ; 

and no other part $input should be selected even the id: part

The value 10.123 is constant and the value AVC13231 changes dynamically.

How can i achieve the above?


回答1:


Here's a solution.

$input = "999 success: id:10.123/AVC13231 | ark:/asf4523/2425fsaf";
$pos1 = strpos($input, 'id:')+3;    // Remove 'id:'
$pos2 = strpos($input, '|')-1;      // Remove space before pipe
$output = substr($input, $pos1, ($pos2 - $pos1));



回答2:


And the mandatory regex solution:

preg_match("/id:([^\s]*)/", $input, $matches);
$output = $matches[1];



回答3:


You could also use:

$data = substr($input, $startpos=(strpos($input, "id:")+3), strpos($input, ' ', $startpos)-$startpos);

Not tested, but the logic is there, just adapt correctly the algorithm...




回答4:


Try this

$input = "999 success: id:10.123/AVC13231 | ark:/asf4523/2425fsaf";

$first_split=explode(" |",$input);
$input_split1=$first_split[0];
$second_split=explode("10.123",$input_split1);
$input_split2=$second_split[1];
$output="10.123".$input_split2;

echo $output;


来源:https://stackoverflow.com/questions/7636319/selecting-a-part-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!