2012-03-30 7 views
1

Je dois remplacer tous les mots avec le nombre de caractères désiré: Avoir cette chaîne:regex remplacer les mots avec certain nombre de caractères

Down the Rabbit Hole Alice was beginning to get very tired of sitting by her sister on the bank and of having nothing to do once or twice she had peeped into the book her sister was reading but it had no pictures or conversations in it and what is the use 

Comment puis-je supprimer tous les mots avec 3 caractères ou moins de chaîne ci-dessus?

$data = preg_replace("/[\w+{0,3}]/m", '', $data); 
+0

Edité, avec mon code ... :( – greenbandit

Répondre

4

Comme ceci:

preg_replace("/\b\w{1,3}\b/", '', $data); 
+1

+1 Et si vous êtes inquiet d'avoir plusieurs espaces après avoir supprimé les mots courts, un second remplacement comme 'preg_replace ('/ \ s + /', '', $ data)' pourrait faire l'affaire – Wiseguy

+0

Cela fonctionne, merci btw, qu'est-ce que le \ b? – greenbandit

+0

@ greenbandit '\ b' est un [wor d frontière] (http://www.regular-expressions.info/wordboundaries.html). Sans lui, trois caractères de mot au milieu d'un mot correspondraient (ainsi vous retireriez "Dow" de "Down", ce qui n'est évidemment pas souhaitable). – Wiseguy

0

Cela a fonctionné pour moi:

$data = "Down the Rabbit Hole Alice was beginning to get very tired of sitting by her sister on the bank and of having nothing to do once or twice she had peeped into the book her sister was reading but it had no pictures or conversations in it and what is the use"; 
$data = preg_replace("/\b\w{1,3}\b/", '', $data); 
echo $data; 

# Down Rabbit Hole Alice beginning very tired sitting sister bank having nothing once twice peeped into book sister reading  pictures conversations what 
+0

En quoi est-ce différent de la réponse @MichaelRushton? – Toto

Questions connexes