Jump to content

Searching for quoted string...in a string.


breakerjump

Recommended Posts

Alright, so this is melting my brain...

 

I have a string, let's say: "Here Are Some Words" and here are some more "And Yet More"

 

How in the hell do I go about ripping whatever is inside those quotes into variables, such that:

Variable One = Here Are Some Words

Variable Two = And Yet More

Link to comment
https://forums.phpfreaks.com/topic/47174-searching-for-quoted-stringin-a-string/
Share on other sites

  • 2 weeks later...

I don't mean to hijack the thread but I’m looking for something like this, the above code gets me about half way to what I’m trying to achieve  :) but I’m struggling to get it how I want/need it.

 

$keywords = explode(" ",$_POST['keywords']);

 

I’m currently using the above code to split keywords up into a array but I would like to keep any string in quotes together, like the above example... but the above example seems to omit the text not in quotes?

 

My current code does this when i input a string like "one two" three four "five six"  :(:

Array
(
    [0] => \"one
    [1] => two\"
    [2] => three
    [3] => four
    [4] => \"five
    [5] => six\"
)

 

I want to get it like this:

 

Array
(
    [0] => one two
    [1] => three
    [2] => four
    [3] => five six
)

 

Again sorry if I’m hijacking.

Ok after some thought I came up with the following, which does what I want it to do.  There's probably an easier way to do it and my coding is a bit "down and dirty" but it gets the job done.

 

<pre><?php

$string = '"Here Are Some Words" and here are some more "And Yet More"';
preg_match_all('/"(.*)"/U', $string, $matches);

// Remove the quoted text from the string.
foreach ($matches[0] as &$value) {
    $string = str_replace($value,"",$string);
}

// Remove annoying white spaces.
$string = trim($string);

// Build the array from the results.
$keywords = array_merge($matches[1], explode(" ",$string));
print_r($keywords);

?></pre>

 

Output:

Array
(
    [0] => Here Are Some Words
    [1] => And Yet More
    [2] => and
    [3] => here
    [4] => are
    [5] => some
    [6] => more
)

 

Comments welcome.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.