2016-01-15 47 views
0

之間我有一個PHP應用程序,節省了數據庫的輸出如下:PHP的Preg匹配,獲取價值的具體模式

::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這個輸出信息。例如下面的範例檢索在同一個地方「排版」和「文字」的任何值:

::i1|0|gx::Lorem::/i1|0|gx:: 
::head1|0|gx::ipsum::/head1|0|gx:: 

但我無言以對用的preg_match語法。

我知道我需要爲每個「標籤」(比如preg_match檢索所有「i1」值,不同的preg_match來檢索所有「head1」等)需要不同的preg匹配。我只需要一個能夠理解正確模式的例子。

此外,在最後一行是一個例子,包含很多不同的字符,如數字,逗號,「%」等,我不確定這是否會混淆語法。

這裏有兩個我的失敗嘗試:

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); 
+0

'''需要逃脫。我認爲'[:'正在被讀作POSIX字符類。你是否試圖對這些進行分組?嘗試在像regex101這樣的網站上運行你的正則表達式。 – chris85

回答

0

希望這將有助於

<?php 
    $str = '::i1|0|gx::Lorem::/i1|0|gx::'; 
    preg_match('/(?<=gx::).*(?=::\/)/', $str); 

您還可以使用preg_match_all()

<?php 
    $str = '::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::'; 

    preg_match_all('/(?<=gx::).*(?=::\/)/', $str, $matches); 
    var_dump($matches); 

(?<=gx::)正回顧後 - 斷言,下面的正則表達式可匹配

斷言,下面的正則表達式可以匹配

::匹配 -

.任何字符(除新行)

*之間的零和無限次,多次儘可能

(?=::\/)正向前查找匹配字符::字面意思

\/匹配字符/字面意思

+0

謝謝,這有助於很多; – user1967509

0

你能想出以下的正則表達式:

::(\w+)[^::]+::(?<content>.*?)::(?=\/\1) 

一個PHP代碼片段和freespacing模式正則表達式的解釋如下所示。查看example for it on regex101

<?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 
) 
*/ 
?>