4

我正在尝试使用 PHP 脚本制作 Slack 斜杠命令。

所以当我输入:

/save someurl.com "This is the caption"

我可以将一个字符串转换为两个不同的变量。

长字符串将作为:

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

我希望能够把它变成:

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

我已经尝试了之前在 Stack Overflow 上搜索的一些正则表达式模式,但可以让任何东西正常工作。

任何帮助深表感谢!

4

4 回答 4

4

如果您知道它将采用该格式,则可以使用以下内容:

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

示例代码:

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

输出:

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

演示

这通过匹配一个或多个非空白字符 ( (\S+))、一个或多个空白字符 ( \s+)、a "、一个或多个字符以非贪婪方式匹配,然后是另一个"

于 2016-02-10T18:21:28.127 回答
2

使用以下正则表达式

(.*?)\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
)
*/
于 2016-02-10T18:20:54.270 回答
0

还有一种方法:

<?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"

?>
于 2016-02-10T18:29:39.603 回答
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
于 2018-03-10T06:20:10.467 回答