views:

46

answers:

4

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.

A: 
preg_match("@twitpic\.com/(\w{6})@", "The url is http://www.twitpic.com/f1462i.  Enjoy.", $m);
$id = $m[1];
mhitza
-1: Do not use regexes when you can avoid them, they are a performance killer.
greg0ire
@greg0ire: Why are you downvoting the *answer* when it was the OP who tagged the question "regex"?
Alan Moore
@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
+3  A: 

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
?>
shamittomar
A: 

You could set it a get

// url = http://www.webaddress.com/id=12351 $id
$id = $_GET['id'];

Unless its from a variable http://php.net/manual/en/function.substr.php

Stevanicus
Stevanicus clearly didn't read the question, lol.
Jorge
+1  A: 
  $string = "http://www.twitpic.com/f1462i" ;
  $id = substr($string,strpos($string, 'twitpic.com')+strlen('twitpic.com')+1,6) ;
  echo $id ;
shikhar