PHP extract text from string - trimming?

I have the following XML:

<id>tag:search.twitter.com,2005:22204349686</id> 

How can I write everything after the second colon of a variable?

eg. 22204349686

+4
source share
8 answers

$var = preg_replace('/^([^:]+:){2}/', '', 'tag:search.twitter.com,2005:22204349686');

I assume that you already have a string without the <id> bits.

Otherwise, for SimpleXML: $var = preg_replace('/^([^:]+:){2}/', '', "{$yourXml->id}");

+1
source
 if(preg_match('#<id>.*?:.*?:(.*?)</id>#',$input,$m)) { $num = $m[1]; } 
+3
source

If you already have only the contents of the tags in the variable $str , you can use explode to get everything from the second : on:

 list(,,$rest) = explode(':', $str, 3); 
+2
source

I assume that you have the contents of the id tag in the variable ( $str ).

 // get last occurence of colon $pos = strrpos($str, ":"); if ($pos !== false) { // get substring of $str from position $pos to the end of $str $result = substr($str, $pos); } else { $result = null; } 
0
source

Use explode and strip_tags :

 list(,,$id) = explode( ':', strip_tags( $input ), 3 ); 
0
source

Parse the XML first with an XML parser. Find the text content of the node ( tag:search.twitter.com,2005:22204349686 ). Then write the appropriate regular expression, e.g.

 <?php $str = 'tag:search.twitter.com,2005:22204349686'; preg_match('#^([^:]+):([^,]+),([0-9]+):([0-9]+)#', $str, $matches); var_dump($matches); 
0
source

Regex seems unacceptable to me for such a simple comparison.

If you don't have identifier tags around the line, you can simply do

 echo trim(strrchr($xml, ':'), ':'); 

If they are, you can use

 $xml = '<id>tag:search.twitter.com,2005:22204349686</id>'; echo filter_var(strrchr($xml, ':'), FILTER_SANITIZE_NUMBER_INT); // 22204349686 

strrchr returns :22204349686</id> , and the filter_var part separates everything that is not a number.

0
source
 function between($t1,$t2,$page) { $p1=stripos($page,$t1); if($p1!==false) { $p2=stripos($page,$t2,$p1+strlen($t1)); } else { return false; } return substr($page,$p1+strlen($t1),$p2-$p1-strlen($t1)); } $x='<id>tag:search.twitter.com,2005:22204349686</id>'; $text=between(',','<',$x); if($text!==false) { //got some text.. } 
-2
source

All Articles