简体   繁体   English

如何使用正则表达式获取字符串的一部分?

[英]How to get part of string with Regular expression?

this is my string: http://www.something.com/path/tt 0425235 /somethingelse/ 这是我的字符串: http : //www.something.com/path/tt 0425235 / somethingelse /

and i need to get just "0425235" (Beetween "tt" and "/") 而且我只需要获取“ 0425235”(在“ tt”和“ /”之间)

Test with:http://rubular.com/ 使用以下网址进行测试:http://rubular.com/

#http://www\.imdb\.com/title/tt(\d+)/#

Simple and perfect ;) 简单而完美;)

<?php
$match = array();
$url = 'http://www.something.com/path/tt0425235/somethingelse/bla/bla/bla/bla/?bla=bla';
preg_match( '/\/path\/([a-z]+([\d]+))+\/?/i' , $url , $match );
print_r( $match );
?>

Bye! 再见!

$url = 'http://www.something.com/path/tt0425235/';

list($id) = preg_split('~^.*/tt(\d+)/$~', $url, 2, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) + array(NULL);

If it can't find your pattern, $id will be NULL . 如果找不到您的模式,则$id将为NULL

/http:\/\/[\w+-_\.]+\/path\/tt(\d+)\//

要么

~http://[\w+-_\.]+/path/tt(\d+)/~

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

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