正则表达式匹配字符串中的两个值,使用 PHP。

huangapple go评论63阅读模式
英文:

Regex match two value from string php

问题

以下是您要翻译的内容:

preg_match_all('/gets\((.*?)\,|\>(.*?)\"/', $string, $matches);

翻译成英文:

preg_match_all('/gets\((.*?)\,|\>(.*?)\"/', $string, $matches);
英文:

Hi i am trying to match two value by regex two conditions, But not able to do.

string is

MorText "gets(183,);inc();" for="text">Sweet" Mo

output trying is array

[
  183,
  "Sweet"
]

php regex code is

 preg_match_all('/gets\((.*?)\,|\>(.*?)\"/', $string, $matches);

答案1

得分: 0

如果我理解正确,您想使用正则表达式从字符串**"gets(183,);inc(); for="text">Sweet"**中匹配两个值。以下是一个应该有效的正则表达式示例:

gets\((\d+),\);inc\(\);.*for="([^"]+)"

这个正则表达式有两个捕获组:

  1. (\d+) 捕获了gets() 函数中的一个或多个数字。
  2. "([^"]+)" 捕获了for 属性中的一个或多个字符,不包括双引号。

以下是一个使用这个正则表达式并提取值的PHP示例代码:

$string = 'gets(183,);inc(); for="text">Sweet';
$pattern = '/gets\((\d+),\);inc\(\);.*for="([^"]+)"/';
if (preg_match($pattern, $string, $matches)) {
    $number = $matches[1]; // 获取gets()函数中的捕获值
    $text = $matches[2]; // 获取for属性中的捕获值
    echo "Number: $number\n";
    echo "Text: $text\n";
} else {
    echo "No match found.\n";
}

此代码将输出:

Number: 183
Text: text
英文:

If I understand correctly, you want to match two values from the string "gets(183,);inc();" for="text">Sweet" using regular expressions. Here's an example regex that should work:

gets\((\d+),\);inc\(\);.*for="([^"]+)"

This regex has two capture groups:

  1. (\d+) captures one or more digits inside the gets() function.
  2. "([^"]+)" captures one or more characters inside the for attribute, excluding the double quotes.

Here's an example PHP code to use this regex and extract the values:

$string = 'gets(183,);inc(); for="text">Sweet';
$pattern = '/gets\((\d+),\);inc\(\);.*for="([^"]+)"/';
if (preg_match($pattern, $string, $matches)) {
    $number = $matches[1]; // Captured value inside gets() function
    $text = $matches[2]; // Captured value inside the for attribute
    echo "Number: $number\n";
    echo "Text: $text\n";
} else {
    echo "No match found.\n";
}

This code will output:

Number: 183
Text: text

答案2

得分: 0

为了达到您想要的输出,您可以使用以下正则表达式:

/gets\((\d+),.*?>(.*?)\"/

PHP示例代码:

$string = 'MorText "gets(183,);inc();" for="text">Sweet" Mo';
preg_match_all('/gets\((\d+),.*?>(.*?)\"/', $string, $matches);
print_r(array_merge($matches[1],$matches[2]));

输出结果:

Array
(
    [0] => 183
    [1] => Sweet
)
英文:

To achieve your wanted output you can use:

/gets\((\d+),.*?>(.*?)\"/

PHP-Example:

$string = 'MorText "gets(183,);inc();" for="text">Sweet" Mo';

preg_match_all('/gets\((\d+),.*?>(.*?)\"/', $string, $matches);
    
print_r(array_merge($matches[1],$matches[2]));

Outputs:

Array
(
    [0] => 183
    [1] => Sweet
)

huangapple
  • 本文由 发表于 2023年3月31日 21:00:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898844.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定