What's the easiest way to grab a 6-character id from a string?
The id will always be after www.twitpic.com/ and will always be 6 characters.
e.g., $string = 'The url is http://www.twitpic.com/f1462i. Enjoy.';
$id = 'f1462i';
Thanks.
greg0ire
23.3k17 gold badges76 silver badges104 bronze badges
asked Aug 22, 2010 at 18:30
3 Answers 3
Here you go. Complete working code without regex
:
<?php
$string = 'The url is http://www.twitpic.com/f1462i. Enjoy.';
$id = substr($string, strpos($string, 'http://www.twitpic.com/')+23, 6);
echo $id; //output: f1462i
?>
answered Aug 22, 2010 at 18:36
$string = "http://www.twitpic.com/f1462i" ;
$id = substr($string,strpos($string, 'twitpic.com')+strlen('twitpic.com')+1,6) ;
echo $id ;
answered Aug 23, 2010 at 8:27
preg_match("@twitpic\.com/(\w{6})@", "The url is http://www.twitpic.com/f1462i. Enjoy.", $m);
$id = $m[1];
answered Aug 22, 2010 at 18:34
-
1-1: Do not use regexes when you can avoid them, they are a performance killer.greg0ire– greg0ire2010年08月22日 18:37:43 +00:00Commented Aug 22, 2010 at 18:37
-
@greg0ire: Why are you downvoting the answer when it was the OP who tagged the question "regex"?Alan Moore– Alan Moore2010年08月23日 04:08:49 +00:00Commented Aug 23, 2010 at 4:08
-
@Alan Moore: because I didn't read the tags... I would cancel this if I could but it seems to be too late. I retag the question, regexes have nothing to do with this.greg0ire– greg0ire2010年08月23日 08:07:47 +00:00Commented Aug 23, 2010 at 8:07
lang-php