PHP Preg Match,获取特定模式之间的值
我有一个php应用程序,它在数据库中保存以下输出:PHP Preg Match,获取特定模式之间的值,php,regex,preg-match,Php,Regex,Preg Match,我有一个php应用程序,它在数据库中保存以下输出: ::cck_gx::gx::/cck_gx:: ::i1|0|gx::Lorem::/i1|0|gx:: ::head1|0|gx::ipsum::/head1|0|gx:: ::tx1|0|gx::dolor, fithos lusec.::/tx1|0|gx:: ::cckend_gx::::/cckend_gx:: ::cck_gx::gx::/cck_gx:: ::i1|1|gx::calendar::/i1|1|gx:: ::head
::cck_gx::gx::/cck_gx::
::i1|0|gx::Lorem::/i1|0|gx::
::head1|0|gx::ipsum::/head1|0|gx::
::tx1|0|gx::dolor, fithos lusec.::/tx1|0|gx::
::cckend_gx::::/cckend_gx::
::cck_gx::gx::/cck_gx::
::i1|1|gx::calendar::/i1|1|gx::
::head1|1|gx::1 Fatura Grátis Por Ano::/head1|1|gx::
::tx1|1|gx::10% de cada mensalidade é reservado, e o valor acumulado até a renovação do Seguro Porto Seguro ou Azul Seguros, é devolvido em forma de desconto. Ou seja, Cliente Conecta pode ter uma fatura de celular grátis por ano.::/tx1|1|gx::
我想使用preg_match从这个输出中检索信息。例如,在下面的示例中,在“Lorem”和“ipsum”的相同位置检索任何值:
::i1|0|gx::Lorem::/i1|0|gx::
::head1|0|gx::ipsum::/head1|0|gx::
但我对preg_match语法一无所知
我知道我需要为每个“标签”使用不同的preg匹配(例如,使用preg_匹配检索所有“i1”值,使用不同的preg_匹配检索所有“head1”值等等)。我只需要一个例子来理解正确的模式
另外,在最后一行是一个例子,有很多不同的字符,如数字、逗号、“%”和其他,我不确定这是否会影响语法
以下是我两次失败的尝试:
preg_match('~[::i1|0|gx::](.*?)[/::i1|0|gx::]~', $maindata->introtext, $match1a);
preg_match('::i1|0|gx::(.*?)::/i1|0|gx::', $maindata->introtext, $match1a);
preg_match('/::i1|0|gx::(.*?)::.i1|0|gx::/', $maindata->introtext, $match1a);
希望这会有所帮助
<?php
$str = '::i1|0|gx::Lorem::/i1|0|gx::';
preg_match('/(?<=gx::).*(?=::\/)/', $str);
(?您可以提出以下正则表达式:
::(\w+)[^::]+::(?<content>.*?)::(?=\/\1)
:(\w+[^:]+:(?*?)::(?=\/\1)
下面显示了一段PHP代码片段以及在freespacing模式下对正则表达式的解释
|
s需要转义。我认为[:
被解读为一个POSIX字符类。您是否也尝试使用这些字符进行分组?请尝试在像regex101这样的网站上运行您的Regex。谢谢,这非常有帮助;
::(\w+)[^::]+::(?<content>.*?)::(?=\/\1)
<?php
$string = '
::cck_gx::gx::/cck_gx::
::i1|0|gx::Lorem::/i1|0|gx::
::head1|0|gx::ipsum::/head1|0|gx::
::tx1|0|gx::dolor, fithos lusec.::/tx1|0|gx::
::cckend_gx::::/cckend_gx::
::cck_gx::gx::/cck_gx::
::i1|1|gx::calendar::/i1|1|gx::
::head1|1|gx::1 Fatura Grátis Por Ano::/head1|1|gx::
';
$regex = '~
::
(\w+)
# tag
[^:]+::
# match everything except a colon, then two colons
(?<content>.*?)
# match everything lazily and capture it in a group called content
::
# two colons
(?=\/\1)
# closing tag with tag captured in group 1
~x';
preg_match_all($regex, $string, $matches);
print_r($matches["content"]);
/* output:
Array
(
[0] => gx
[1] => Lorem
[2] => ipsum
[3] => dolor, fithos lusec.
[4] =>
[5] => gx
[6] => calendar
[7] => 1 Fatura Grátis Por Ano
)
*/
?>