Dumb_Shock
Dumb_Shock

Reputation: 1008

Selecting a part of a string

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?

Upvotes: 2

Views: 150

Answers (4)

Wasim Karani
Wasim Karani

Reputation: 8886

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;

Upvotes: 0

JRL
JRL

Reputation: 78033

And the mandatory regex solution:

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

Upvotes: 3

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

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...

Upvotes: 1

Jeff Lambert
Jeff Lambert

Reputation: 24661

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));

Upvotes: 4

Related Questions