Regular Expression Q.

Discussion in 'PHP' started by alphacooler, Jun 30, 2007.

  1. #1
    I'm a n00b when it comes to regular expressions. I can do the basics, but need some help with this one.

    Say I have a paragraph with the following sentence:

    You need to replace the carburetor, transmission, spark plugs, both driver and passenger mirrors, and tailights. This should come out to around $800.
    Code (markup):
    I want to be able to pull out all the comma separated words/phrases and then re-order them and put them back into the paragraph..

    So I would end up with something like:
    
    You need to replace the both driver and passenger mirrors, transmission, spark plugs, and tailights, carburetor. This should come out to around $800.
    Code (markup):
    Any ideas?
     
    alphacooler, Jun 30, 2007 IP
  2. amorph

    amorph Peon

    Messages:
    200
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You don't need a regex for that. use str_replace where you can since it's faster. Edit the $symbols array to control what exactly you want out of your string.

    $string = 'You need to replace the carburetor, transmission, spark plugs, both driver and passenger mirrors, and tailights. This should come out to around $800.';
    	
    	function removeSymbols( $string ) 
    	{	
    		$symbols = array('/','\\','\'','"',',','.','<','>','?',';',':','[',']','{','}','|','=','+','-','_',')','(','*','&','^','%','$','#','@','!','~','`');
    		for ($i = 0; $i < sizeof($symbols); $i++)
    		{
    			$string = str_replace($symbols[$i],'',$string);
    		}			
    		return trim($string);
    	}
    
    	$string = removeSymbols( $string );
    
    	echo $string;
    PHP:
     
    amorph, Jun 30, 2007 IP
  3. alphacooler

    alphacooler Peon

    Messages:
    70
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    That is the thing,

    I'm not trying to replace certain words, but rather I want to look for comma separated lists (of *any* words/phrases...not specific ones) in order to automatically shuffle their order and put them back into the sentence.

    This most definitely calls for a regular expression.
     
    alphacooler, Jun 30, 2007 IP
  4. ansi

    ansi Well-Known Member

    Messages:
    1,483
    Likes Received:
    65
    Best Answers:
    0
    Trophy Points:
    100
    #4
    this should work. it will find any word or number proceeded by a ,

    
    /([a-z0-9]+(?=(?:\s{1,})?,(?:\s{1,})?))/i
    
    PHP:
    now there's probably a few other ways and perhaps better ones as well but hopefully this will get you started.
     
    ansi, Jun 30, 2007 IP