开发者

How to extract a word using regex in php?

开发者 https://www.devze.com 2022-12-25 08:09 出处:网络
How do I extract foo from the following URL and store it in a varialbe, using regex in php? http://example.com/pages/foo/inside.php

How do I extract foo from the following URL and store it in a varialbe, using regex in php?

http://example.com/pages/foo/inside.php
开发者_开发问答

I googled quite a bit for an answer but most regex examples were too complex for me to understand.


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


Well, there could be multiple solutions, based on what rule you want the foo to be extracted. As you didn't specify it yet, I'll just guess that you want to get the folder name of the current file (if that's wrong, please expand your question).

<?php
$str = 'http://example.com/pages/foo/inside.php';
preg_match( '#/([^/]+)/[^/]+$#', $str, $match );
print_r( $match );
?>


If the first part is invariant:

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

The main part is ([^/]+) which matches everything which is not a slash (/). That is, we're matching until finding the next slash or end of the string (if the "foo" part can be the last).


$str = 'http://example.com/pages/foo/inside.php';
$s=parse_url($str);
$whatiwant=explode("/",$s['path']);
print $whatiwant[2];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号