Php preg_split ignore comma in specific line

I need help. I want to ignore the comma in a specific line. This is a comma-separated csv file, but the name has a comma, and I need to ignore it.

I got

<?php $pattern = '/([\\W,\\s]+Inc.])|[,]/'; $subject = 'hypertext language, programming, Amazon, Inc., 100'; $limit = -1; $flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE; $result = preg_split ($pattern, $subject, $limit, $flags); ?> 

Result

 $result (php code): <?php array ( 0 => 'hypertext language', 1 => ' programming', 2 => ' Amazon', 3 => ' Inc.', 4 => ' 100', ); ?> 

And I want the result to be

 $result (php code): <?php array ( 0 => 'hypertext language', 1 => ' programming', 2 => ' Amazon, Inc.', 3 => ' 100', ); ?> 

Thank you for your help:)

+5
source share
2 answers

Note that [\W,\s] = \W , since \W matches any char that is not a letter, number, or underscore. However, it seems that you just want to divide by , followed by a space * * Inc. .

To achieve this, you can use negative browsing :

 /,(?!\s*Inc\.)/ ^^^^^^^^^^^^ 

Watch the regex demo

(?!\s*Inc\.) will not be able to fulfill any match if there are 0+ spaces ( \s* ) followed by a sequence of letter characters Inc. after them.

+3
source

From your tutorial, if I pull Amazon information as CSV, I get the following format. Then you can parse one of Php's own functions. This shows that you do not need to use explode or regex to process this data. Use the correct tool for the job:

 <?php $csv =<<<CSV "amzn","Amazon.com, Inc.",765.56,"11/2/2016","4:00pm","-19.85 - -2.53%",10985 CSV; $array = str_getcsv($csv); var_dump($array); 

Output:

 array (size=7) 0 => string 'amzn' (length=4) 1 => string 'Amazon.com, Inc.' (length=16) 2 => string '765.56' (length=6) 3 => string '11/2/2016' (length=9) 4 => string '4:00pm' (length=6) 5 => string '-19.85 - -2.53%' (length=15) 6 => string '10985' (length=5) 
+1
source

Source: https://habr.com/ru/post/1259196/


All Articles