2017-08-17 5 views
-1

C'est ce que j'ai jusqu'à présent:PHP Mettre Span classe dans les supports regex

$phones = "Samsung Galaxy S8~LG G6~iPhone 7 Plus~ Motorola Z2"; 

$phones = str_replace("Galaxy S", '<span class="galaxy">galaxy</span>', $phones); 

$value = preg_replace('/(\d+.*?)(~)/', '($1)$2', $phones . "~"); 

$value = "<li>". str_replace("~", ",</li><li>", substr($value,0,-1)) . "</li>"; 

Echo $value; 

et le résultat est:

  • Samsung galaxie (8),
  • LG G (6),
  • iPhone (7 Plus),
  • Motorola Z (2)

Ce que je suis en train de faire est de mettre la classe span à l'intérieur des crochets afin qu'il soit:

  • Samsung (galaxie 8),
  • LG G (6),
  • iPhone (7 plus),
  • Motorola Z (2)

Merci

Répondre

1

Pattern Demo/Explanation

code: (Demo)

$phone='Samsung Galaxy S8~LG G6~iPhone 7 Plus~ Motorola Z2'; 
$match='/Galaxy S(\d+)/'; 
$replace='(<span class="galaxy">galaxy</span> $1)'; 
echo preg_replace($match,$replace,$phone); 

Sortie non calculé:

Samsung (<span class="galaxy">galaxy</span> 8)~LG G6~iPhone 7 Plus~ Motorola Z2 

Voici le bloc complet <ul>:

$phone='Samsung Galaxy S8~LG G6~iPhone 7 Plus~ Motorola Z2'; 
$match='/Galaxy S(\d+)/'; 
$replace='(<span class="galaxy">galaxy</span> $1)'; 
echo '<ul><li>',str_replace('~',',</li><li>',preg_replace($match,$replace,$phone)),'</li></ul>'; 

sortie non calculé:

<ul><li>Samsung (<span class="galaxy">galaxy</span> 8),</li><li>LG G6,</li><li>iPhone 7 Plus,</li><li> Motorola Z2</li></ul> 


Altération final:

$phones="Samsung Galaxy S8~LG G6~iPhone 7 Plus~ Motorola Z2"; 
$patterns=[ 
    '/(?:Galaxy S)?\d[^~]*/', // match (optional Galaxy S), number, optional trailing text 
    '/~ ?/', // match delimiter and optional trailing space (at Motorola) 
    '/Galaxy S/' // literally match Galaxy S 
]; 
$replacements=[ 
    '($0)', // wrap full string match in parentheses 
    '</li><li>', // use closing and opening li tags as new delimiter 
    '<span class="galaxy">Galaxy</span> ' // tagged text (note: G & space after </span>) 
]; 
$full_list='<ul><li>'.preg_replace($patterns,$replacements,$phones).'</li></ul>'; 
echo $full_list; 

Sortie non calculé:

<ul><li>Samsung (<span class="galaxy">galaxy</span> 8)</li><li>LG G(6)</li><li>iPhone (7 Plus)</li><li>Motorola Z(2)</li></ul>