如何在第 n 个单词出现之间获取子字符串


How to Fetch the sub string between nth occurences of words.?

e.g

main_string ="我有一个芒果,<'价格'> (abcdef) <'/price'> 10,一根香蕉<'/价格'> (ghijk) <'/price'> 15 和一个<'/价格'> (lmnop) <'/价格'> 20 的苹果。所以花费的总金额是 45 卢比";

我想找到介于"<'价格'>"的第 3 次出现和"第 3 次出现>之间的子字符串

即输出 = (lmnop)

溶液

注意:在主字符串中,标签不是作为字符串出现的,所以我一直使用引号,例如<'价格'>和<'/价格'>。解决方案仅在从标签中删除引号后有效。

试试这个:

$string = 'I have a mango which <price>1111</price> 10, a banana which <price>3333</price> 15 and an apple which <price>5555</price> 20. So the total amount spent is Rs 45';
$pattern = '/'<price'>(.*?)'<'/price'>/';
$matches = array();
preg_match_all($pattern, $string, $matches);
var_dump($matches);
var_dump($matches[1][2]);

结果是:

array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(19) "<price>1111</price>"
    [1]=>
    string(19) "<price>3333</price>"
    [2]=>
    string(19) "<price>5555</price>"
  }
  [1]=>
  array(3) {
    [0]=>
    string(4) "1111"
    [1]=>
    string(4) "3333"
    [2]=>
    string(4) "5555"
  }
}
string(4) "5555" // <-- that's what you want