php 如何从PHP中的字符串中提取子字符串直到它到达某个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4674097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract a substring from a string in PHP until it reaches a certain character?
提问by Hyman Roscoe
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.
我有一个 PHP 应用程序的一部分,它评估用户输入的长字符串,并提取一个始终以 20 个字符开头的数字到用户提供的字符串中。
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?
如何使用 PHP 子字符串函数从特定点开始提取子字符串,并在它遇到双引号时结束?
Thanks in advance.
提前致谢。
回答by Gumbo
You can use strpos
to get the first position of "
from the position 20 on:
您可以使用从位置 20 开始strpos
获取第一个位置"
:
$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 needlecannot be found in haystack.
第三个参数的计算是必要的,因为substr
期望子串的长度而不是结束位置。还要注意的是substr
回报率false
,如果针不能找到草垛。
回答by Nickolodeon
$nLast = strpos($userString , '"');
substr($userString, 0, $nLast);
回答by dev-null-dweller
find first occurrence of double quote after 20 chars, substract 19 - that gives you length of desired substring:
在 20 个字符后找到第一次出现的双引号,减去 19 - 这给出了所需子字符串的长度:
$dq = strpos($string,'"',19); //19 is index of 20th char
$desired_string = substr($string,19,$dq-19);
回答by Nick Rolando
Going to just add on to Gumbo's answer in case you need help with the substring function:
如果您需要 substring 函数的帮助,只需添加 Gumbo 的答案:
$pos = strpos($str, '"', 20);
$substring = substr($str, 20, $pos);
回答by Jason Benson
<?
$str = substring($input, 20, strpos($input, '"') - 20);
echo $str;
?>
Or something like that etc.
或者类似的东西等等。