获取较大字符串中两个字符串之间的字符[重复]

问题描述 投票:0回答:3

我希望能够在 PHP 中使用正则表达式来提取 以下 html 片段中的“Ruby9”

on Red Hot Ruby Jewelry<br>Code: Ruby9<br>

有时“代码”将是字母数字、数字或只是字母。

php regex text-extraction
3个回答
1
投票

尝试这个正则表达式:

$str = "on Red Hot Ruby Jewelry<br>Code: Ruby9<br>";

$pattern  = "/Code: ([^<]+)/"; // matches anything up to first '<'
if(preg_match($pattern, $str, $matches)) {
    $code = $matches[1]; // matches[0] is full string, matches[1] is parenthesized match
} else {
    // failed to match code
}

1
投票
if (preg_match('/(?<=: ).+(?=<)/', $subject, $regs)) {
    // ow right! match!
    $result = $regs[0];
} else {
    // my bad... no match...
}

0
投票

如果模式始终相同,则正则表达式将如下所示:

"<br>Code: ([a-zA-Z0-9]+)<br>"

这将捕获
Code: 之后和
之前的任何字母或字母数字或数字字符串。尝试以下操作:

<?php
$subject = "on Red Hot Ruby Jewelry<br>Code: Ruby9<br>";
$pattern = '<br>Code: ([a-zA-Z0-9]+)<br>';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
© www.soinside.com 2019 - 2024. All rights reserved.