SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Wizard Zaggs's Avatar
    Join Date
    Feb 2005
    Posts
    1,048
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    preg_match question

    Hi Guys,

    I need to extract phrases / words into an array from a string. The current code I am using is shown below, but it doesn't work as intended.

    Here is the output i would like to see from the folowing string:

    STRING:
    Code:
    "technical writer" "documentation manager" "technical author"
    Output should be:
    PHP Code:
    <?php
    Array
    (
        [
    0] => technical writer
        
    [1] => documentation manager
        
    [2] => technical author
    )
    ?>
    STRING:
    Code:
    "technical writer" and "documentation manager" and "technical author"
    Output should be:
    PHP Code:
    <?php
    Array
    (
        [
    0] => technical writer
        
    [1] => and
        [
    2] => documentation manager
        
    [3] => and
        [
    4] => technical author
    )
    ?>

  2. #2
    SitePoint Enthusiast
    Join Date
    Apr 2008
    Location
    The Netherlands
    Posts
    44
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I am not so experienced with regular expressions, but I have come up with this.
    Only problem is that it puts the starting and ending space also in the array value.

    PHP Code:
    preg_match_all('/[a-z\s]+/i','"technical writer" and or "documentation manager" and "technical author"',$matches);
    echo 
    '<pre>';
    print_r($matches);
    echo 
    '</pre>'
    Outputs:
    PHP Code:
    Array
    (
        [
    0] => Array
            (
                [
    0] => technical writer
                
    [1] =>  and or 
                [
    2] => documentation manager
                
    [3] =>  and 
                [
    4] => technical author
            
    )


    So you have to look for yourself how to fix the expression, to get rid of the spaces. Also you have to modify it to your needs offcourse.

  3. #3
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    70 Post(s)
    Tagged
    0 Thread(s)
    Simple answer: Dont preg_match, preg_split.
    PHP Code:
    $results preg_split('~\"(.*?)\"~',$test,-1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); 
    As far as removing the spaces, array_map('trim',$results);
    Never grow up. The instant you do, you lose all ability to imagine great things, for fear of reality crashing in.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •