Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

substring

php

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.

like image 421
Jack Roscoe Avatar asked Jan 12 '11 21:01

Jack Roscoe


People also ask

How do you get the part of a string before a specific character?

Use the substring() method to get the substring before a specific character, e.g. const before = str. substring(0, str. indexOf('_')); . The substring method will return a new string containing the part of the string before the specified character.

How split a string after a specific character in PHP?

explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.

How do I get everything after a specific character in PHP?

or: $text = end((explode('_', '233718_This_is_a_string', 2))); By specifying 2 for the limit parameter in explode() , it returns array with 2 maximum elements separated by the string delimiter. Returning 2nd element ( [1] ), will give the rest of string.


2 Answers

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.

like image 144
Gumbo Avatar answered Oct 06 '22 13:10

Gumbo


$nLast = strpos($userString , '"');
substr($userString, 0, $nLast);
like image 43
Nickolodeon Avatar answered Oct 06 '22 13:10

Nickolodeon