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

I have a part of a PHP application that evaluates a long line input by a user and extracts a number that always starts 20 characters in the line that the user provides.

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

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

Thanks in advance.

+6
substring php
source share
5 answers

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

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

Then this position can be used to get the substring:

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

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

+11
source share
 $nLast = strpos($userString , '"'); substr($userString, 0, $nLast); 
+1
source share
 <? $str = substring($input, 20, strpos($input, '"') - 20); echo $str; ?> 

Or something like that, etc.

0
source share

find the first occurrence of a double quote after 20 characters, subtract 19 - this gives you the length of the desired substring:

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

Going to the Gumbo answer is simple if you need help with a substring:

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

All Articles