如何从PHP的字符串中提取子字符串,直到达到某个字符? [英] How to extract a substring from a string in PHP until it reaches a certain character?

查看:471
本文介绍了如何从PHP的字符串中提取子字符串,直到达到某个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP应用程序的一部分,该应用程序评估用户输入的长字符串,并提取一个始终以20个字符开头的数字到用户提供的字符串中.

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 (").

如何使用PHP子字符串函数提取一个从特定点开始并在其引起双引号时结束的子字符串?

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?

谢谢.

推荐答案

您可以使用 strpos 来获得"从位置20开始:

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

第三个参数的计算是必需的,因为 substr 期望子字符串的长度而不是结束位置.另请注意,如果在 haystack 中找不到 needle ,则substr返回false.

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.

这篇关于如何从PHP的字符串中提取子字符串,直到达到某个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆