PHP - trying to get text only inside quotes

I am trying to make a Slack slash command using a PHP script.

So when I type:

/save someurl.com "This is the caption"

I can convert one string to two different variables.

A long line will look like:

https://someurl.com "This is the caption"

I want to be able to turn this into:

$url = https://someurl.com;
$caption = This is the caption;

I tried some regex patterns from a previous search here on Stack Overflow, but could get something to work correctly.

Any help is much appreciated!

+4
source share
4 answers

If you know that it will be in this format, you can use something like this:

(\S+)\s+"(.+?)"

Code example:

$string = 'someurl.com "This is the caption"';
preg_match('~(\S+)\s+"(.+?)"~', $string, $matches);
var_dump(
    $matches
);

Output:

array(3) {
  [0] =>
  string(33) "someurl.com "This is the caption""
  [1] =>
  string(11) "someurl.com"
  [2] =>
  string(19) "This is the caption"
}

Demo .

((\S+)), (\s+), a ", , ".

+4

(.*?)\s"(.*?)"

, , .

:

$string = 'https://someurl.com "This is the caption"';

preg_match('/(.*?)\s"(.*?)"/', $string, $matches);

print_r($matches);
/* Output:
Array
(
    [0] => https://someurl.com "This is the caption"
    [1] => https://someurl.com
    [2] => This is the caption
)
*/
+2

:

<?php
$string = 'https://someurl.com "This is the caption"';
$regex = '~\s+(?=")~';
# looks for a whitespace where a double quote follows immediately
$parts = preg_split($regex, $string);
list($url, $caption) = preg_split($regex, $string);
echo "URL: $url, Caption: $caption";
// output: URL: https://someurl.com, Caption: "This is the caption"

?>
0

Slack, - :
/save someurl.com "This is a \"quote\" in the caption"

:
https://someurl.com "This is a \"quote\" in the caption"

, , .

, , , :

~(\S+) "(.+)"~

: ()

$input = 'https://someurl.com "This is a \"quote\" in the caption"';
list($url, $caption)=(preg_match('~(\S+) "(.+)"~', $input, $out) ? array_slice($out,1) : ['','']);
echo "url: $url\ncaption: $caption";

:

url: https://someurl.com
caption: This is a \"quote\" in the caption
0

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


All Articles