PHP-尝试仅在引号内获取文本
我正在尝试使用PHP脚本生成一个Slack斜杠命令 所以当我打字时:PHP-尝试仅在引号内获取文本,php,regex,slack,Php,Regex,Slack,我正在尝试使用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; 我在堆栈溢出上尝试了以前搜索中的一些正则表达式模
/save someurl.com "This is the caption"
我可以把一个字符串转换成两个不同的变量
长字符串将以以下形式出现:
https://someurl.com "This is the caption"
我希望能够将其转化为:
$url = https://someurl.com;
$caption = This is the caption;
我在堆栈溢出上尝试了以前搜索中的一些正则表达式模式,但可以得到任何正确的结果
非常感谢您的帮助 使用以下正则表达式
(.*?)\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
)
*/
如果您知道它将采用这种格式,您可以使用如下内容:
(\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"
}
url: https://someurl.com
caption: This is a \"quote\" in the caption
这是通过匹配一个或多个非空白字符((\S+
)、一个或多个空白字符(\S+
)、一个“
、一个或多个非贪婪的字符,然后是另一个”
另一种方法:
<?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"
?>
我不使用Slack,但如果可以输入如下内容:
/save someurl.com“这是标题“
导致此长字符串:
https://someurl.com “这是标题“
然后,寻找双引号的惰性模式将失败
尽管如此,贪婪模式比懒惰模式更有效,因此我建议在所有情况下使用以下模式:
~(\S+) "(.+)"~
代码:()
输出:
array(3) {
[0] =>
string(33) "someurl.com "This is the caption""
[1] =>
string(11) "someurl.com"
[2] =>
string(19) "This is the caption"
}
url: https://someurl.com
caption: This is a \"quote\" in the caption
随正则表达式返回的标题如下:`$slackMessage=“””$_POST['text']。"'"; $regexpatern='~(S+)\S+(.+)~';preg_match($regexpatern、$slackMessage、$matches)$link=$matches[1]$title=$matches[2]`@MattLewis您的上一条评论没有显示问题,但是(从您现在删除的评论中)看起来您有一个Unicode智能引号,而不是一个直接的、正常的引号。解决这个问题的最简单方法是使用这个正则表达式:(\S+)\S++\S(+.+?)\S
。请尝试一下并告诉我它是否有效。我收到一个错误:preg\u match():未知修饰符“\”
$regexpatern=”(\S+\S++?)\S)@但您仍然需要分隔符(~
,在本例中),如~(\S+)\S++\S(+.+?)\S~
。我不是故意要把它们拿走的。因此,实际的代码行将是preg_match('~(S+)\S++\S(+.+?)\S~,$string,$matches)代码>没问题,我对PHP很陌生。我认为,当我们在原始字符串周围添加单引号时,会破坏我需要处理的url。当我的另一个函数运行以获取基于该url的信息时,我遇到了一个错误<代码>警告:文件\u获取\u内容('http://somurl.com):无法打开流