2009-06-04 7 views
2

non gourmand Hey tout ce que j'ai une grande chaîne HTML commeRegex aide, avide contre

<a style="background: rgb(100, 101, 43) none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-backg round-inline-policy: -moz-initial;" href="#">swatch4</a> 
<a style="background: rgb(34, 68, 33) none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-b ackground-inline-policy: -moz-initial;" href="#">swatch5</a> 
<a style="background: rgb(11, 38, 68) none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -m oz-background-inline-policy: -moz-initial;" href="#">swatch6</a> 
<a style="background: rgb(39, 11, 60) none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial ; -moz-background-inline-policy: -moz-initial;" href="#">swatch7</a> 

... Il y a beaucoup de ces entrées ...

Ce que je voudrais terminer avec un tableau php

$colors = array(
'rgb(34, 34, 33)', 
'rgb(11, 38, 68)', 
... 
); 

etc.

l'étape j'ai besoin d'aide avec l'extraction de la partie rgb de la chaîne. J'ai des problèmes avec mes regex qui mangent trop de la ficelle. Anyhelp serait apprécié, je voudrais descendre et apprendre à faire (par opposition à juste l'avoir fait). J'utilise vim btw.

Merci

Répondre

6

Le regex simple

(rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)) 

Chaque "\ s * \ d {1,3} \ s *," signifie:

  • espace de correspondance (espace comme '', ou des onglets, comme molf dit dans les commentaires, dans un nombre de 0 à inf)
  • correspondre à un chiffre (de 1 chiffre jusqu'à 3 chiffres parce que vous allez de 0 à 255)
  • rencontres autres espaces
  • correspondent à une virgule (,)

Vous pouvez utiliser le code de Paolo pour la partie de tableau.

+4

Je remplacerais les espaces avec \ s *, d'une part pour clarifier l'intention (correspond à aucun espace), et d'autre part parce qu'il permettra également les onglets. – molf

+0

Vous avez raison, après mise à jour. Merci –

0
preg_match_all('/rgb\(\d{1,3}, \d{1,3}, \d{1,3}\)/', $string, $matches); 
print_r($matches); 

Si vous n'êtes pas sûr de l'espacement, utilisez:

preg_match_all('/rgb\(\d{1,3},\s?\d{1,3},\s?\d{1,3}\)/', $string, $matches); 
print_r($matches);