简体   繁体   English

在字符串中的特定字符后获取值

[英]Get value after particular character in string

I have a string as follows 我有一个字符串如下

$str = 'asdasdasd,sdfsdfsdf myNumber=1234, 2323 dfdfdf9898 sdfsdfdsf 234';

I'd like to return the digits within myNumber=1234 . 我想返回myNumber=1234内的数字。

Desired Outcome 期望的结果

$str = '1234';

I currently use the following regex preg_replace('/\\myNumber=\\d+/', '', $y) to replace when required, which works perfectly, but I'm not sure how I could use this to extract the numbers after the = sign from myNumber=1234 ? 目前,我在需要时使用以下正则表达式preg_replace('/\\myNumber=\\d+/', '', $y)进行替换,效果很好,但是我不确定如何使用它来提取数字。 =来自myNumber=1234符号?

You could use the following function: 您可以使用以下功能:

function getStringBetween($str, $from, $to)
{
    $sub = substr($str, strpos($str, $from) + strlen($from), strlen($str));
    return substr($sub, 0, strpos($sub, $to));
}

Then you can use it this way: 然后,您可以通过以下方式使用它:

$a = getStringBetween($str, 'myNumber=', ',');

which will give you the output 1234 since its between the given strings. 这将为您提供输出1234,因为它在给定字符串之间。

You can use a preg_match with the following regex: 您可以将preg_match与以下正则表达式配合使用:

\bmyNumber=(\d+)

See the regex demo 正则表达式演示

The value will be available in Group 1. (\\d+) matches and captures 1+ digits into a group that will be part of the resulting array. 该值将在组1中可用。 (\\d+)匹配并捕获 1+个数字到组中,该组将成为结果数组的一部分。

Demo : 演示

$re = '~\bmyNumber=(\d+)~'; 
$str = "asdasdasd,sdfsdfsdf myNumber=1234, 2323 dfdfdf9898 sdfsdfdsf 234"; 
preg_match($re, $str, $m);
echo $m[1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM