繁体   English   中英

如何在php中使用正则表达式提取单词?

[英]How to extract a word using regex in php?

如何使用以下php中的regex从以下URL中提取foo并将其存储在varialbe中?

http://example.com/pages/foo/inside.php

我在谷歌上搜索了很多答案,但是大多数正则表达式示例太复杂了,以至于我无法理解。

preg_match('~pages/(.+?)/~', "http://example.com/pages/foo/inside.php", $matches);
echo $matches[1];

如果第一部分是不变的:

$s = 'http://example.com/pages/foo/inside.php';
preg_match('@^http://example.com/pages/([^/]+).*$@', $s, $matches);
$foo = $matches[1];

主要部分是([^/]+) ,它匹配所有斜杠( / )。 也就是说,我们一直进行匹配,直到找到字符串的下一个斜杠或结尾(如果“ foo”部分可以是最后一个)。

嗯,根据您要提取foo规则,可能有多种解决方案。 由于您尚未指定,我只是猜测您要获取当前文件的文件夹名称(如果不正确,请扩展您的问题)。

<?php
$str = 'http://example.com/pages/foo/inside.php';
preg_match( '#/([^/]+)/[^/]+$#', $str, $match );
print_r( $match );
?>
$str = 'http://example.com/pages/foo/inside.php';
$s=parse_url($str);
$whatiwant=explode("/",$s['path']);
print $whatiwant[2];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM