【发布时间】:2016-09-26 14:49:54
【问题描述】:
我目前正在尝试格式化 Brandname 的某些部分,但我无法获取需要格式化的部分,例如:
BrandTest®BrandBottle®BrandJuice®
我想要Brand 和® 之间的部分。
我目前尝试过类似:/(?=(Brand))+(.*)+(®)/
但是除了中间的部分,我什么都得到了。
【问题讨论】:
-
您不太了解什么是前瞻。
我目前正在尝试格式化 Brandname 的某些部分,但我无法获取需要格式化的部分,例如:
BrandTest®BrandBottle®BrandJuice®
我想要Brand 和® 之间的部分。
我目前尝试过类似:/(?=(Brand))+(.*)+(®)/
但是除了中间的部分,我什么都得到了。
【问题讨论】:
你可以改变你的正则表达式来使用它:
Brand(.*?)®
php代码
$re = "/Brand(.*?)®/";
$str = "BrandTest® BrandBottle® BrandJuice®";
preg_match_all($re, $str, $matches);
【讨论】:
可能是这样的:
<?php
$brands = 'BrandTest® BrandBottle® BrandJuice®';
$brands = explode('Brand', $brands);
//you will get each brand in an array as:
//"Test®", "Bottle®", "Juice®"
?>
如果您不想要®,那么这可能会帮助https://stackoverflow.com/a/9826656/4977144
【讨论】:
将其汇总到一个方法中并返回您的结果:
function getQueryPiece($queryString) {
preg_match('/\?\=Brand(.*)®/',$queryString,$matches);
return $matches[1];
}
getQueryPiece("?=BrandBottle®"); // string(6) Bottle
getQueryPiece("?=BrandTest®"); // string(4) Test
getQueryPiece("?=BrandJuice®"); // string(5) Juice
这仅定义了 1 个捕获组(?=Brand 和 ® 之间的字符串片段)。如果您还需要捕获其他部分,只需将每个部分包裹在括号中:'/(\?\=Brand)(.*)(®)/' 但是这将改变该部分在$matches 数组中的位置。它将是位置 2。
我相信您的模式中最初的问题是使用“?”的结果未转义。问号在正则表达式中有特殊含义。这是一篇很好的文章:Regex question mark
【讨论】: