Jack Roscoe
Jack Roscoe

Reputation: 4333

How to extract a substring from a string in PHP until it reaches a certain character?

I have part of a PHP application which assess a long string input by the user, and extracts a number which always begins 20 characters into the string the user supplies.

The only problem is that I don't know how long the number for each user will be, all I do know is the end of the number is always followed by a double quote (").

How can I use the PHP substring function to extract a substring starting form a specific point, and ending when it hits a double quote?

Thanks in advance.

Upvotes: 6

Views: 20579

Answers (5)

Nick Rolando
Nick Rolando

Reputation: 26177

Going to just add on to Gumbo's answer in case you need help with the substring function:

$pos = strpos($str, '"', 20);
$substring = substr($str, 20, $pos);

Upvotes: 0

dev-null-dweller
dev-null-dweller

Reputation: 29482

find first occurrence of double quote after 20 chars, substract 19 - that gives you length of desired substring:

$dq = strpos($string,'"',19); //19 is index of 20th char
$desired_string = substr($string,19,$dq-19);

Upvotes: 0

Nickolodeon
Nickolodeon

Reputation: 2956

$nLast = strpos($userString , '"');
substr($userString, 0, $nLast);

Upvotes: 1

Jason Benson
Jason Benson

Reputation: 3399

<?

$str = substring($input, 20, strpos($input, '"') - 20);
echo $str;

?>

Or something like that etc.

Upvotes: 0

Gumbo
Gumbo

Reputation: 655707

You can use strpos to get the first position of " from the position 20 on:

$pos = strpos($str, '"', 20);

That position can then be used to get the substring:

if ($pos !== false) {
    // " found after position 20
    $substr = substr($str, 20, $pos-20-1);
}

The calculation for the third parameter is necessary as substr expects the length of the substring and not the end position. Also note that substr returns false if needle cannot be found in haystack.

Upvotes: 11

Related Questions