Home > Back-end >  Prevent a sentence inside double quotations to explode
Prevent a sentence inside double quotations to explode

Time:10-29

I want to prevent exploding a sentence inside a quotations/double quotations. Tried to play with preg_match but I can't make it to work: Here's an example:

$string = "[categoryhome section_title='Categories' column_1_title='Gift Certificates']";
$temp = explode(" ", $string);

**Current Output:**
array (
  0 => '[categoryhome',
  1 => 'section_title="Categories"',
  2 => 'column_1_title="Gift',
  3 => 'Certificates"]',
)  

**Expected Output:**
array (
  0 => '[categoryhome',
  1 => 'section_title="Categories"',
  2 => 'column_1_title="Gift Certificates"]',
)  

CodePudding user response:

You can write a custom parser.

<?php

$string ='[categoryhome section_title="Categories" column_1_title="Gift Certificates"]';
// or $string ="[categoryhome section_title='Categories' column_1_title='Gift Certificates']";

$parts = [];
$acc = "";
$in_quotes = false;
for ($i = 0; $i < strlen($string);   $i) {
    $c = $string[$i];
    if ($c === '"') {
        $in_quotes = !$in_quotes;
    }
    if (!$in_quotes && $c === ' ') {
        $parts[] = $acc;
        $acc = "";
    } else {
        $acc .= $c;
    }
}
$parts[] = $acc;


var_dump($parts);

CodePudding user response:

With regex assuming that there is one string followed by two key='value' all separated by one space:

$string = "[categoryhome section_title='Categories' column_1_title='Gift Certificates']";

$success = preg_match_all("/\[(\S ) (\S ='[^'] ') (\S ='[^'] ')]$/", $string, $matches);

print_r($matches);

This will print (note that item 0 contains the input string):

Array
(
    [0] => Array
        (
            [0] => [categoryhome section_title='Categories' column_1_title='Gift Certificates'
        )

    [1] => Array
        (
            [0] => categoryhome
        )

    [2] => Array
        (
            [0] => section_title='Categories'
        )

    [3] => Array
        (
            [0] => column_1_title='Gift Certificates'
        )

)
  •  Tags:  
  • php
  • Related