php - the fastest way to replace (and store in array) links in the text with their order numbers -


there $str string may contain html text including <a >link</a> tags.

i want store links in array , set proper changes in $str.

for example, string:

$str="some text <a href='/review/'>review</a> here <a class='abc' href='/about/'>link2</a> hahaha"; 

we get:

linkarray[0]="<a href='/review/'>review</a>"; positionarray[0] = 10;//position of first link in string  linkarray[1]="<a class='abc' href='/about/'>link2</a>"; positionarray[1]=45;//position of second link in string  $changedstr="some text [[0]] here [[1]] hahaha"; 

is there faster way (the performance) that, running through whole string using for?

this can done preg_match_all preg_offset_capture flag.

e.g.

$str="some text <a href='/review/'>review</a> here <a class='abc' href='/about/'>link2</a> hahaha"; preg_match_all("|<[^>]+>(.*)</[^>]+>|u",$str,$out,preg_offset_capture);  var_dump($out); 

here output array $out. preg_offset_capture captures offset in string pattern starts.

the above code output:

array (size=2)0 =>   array (size=2)   0 =>      array (size=2)       0 => string '<a href='/review/'>review</a>' (length=29)       1 => int 10   1 =>      array (size=2)       0 => string '<a class='abc' href='/about/'>link2</a>' (length=39)       1 => int 45 1 =>   array (size=2)   0 =>      array (size=2)       0 => string 'review' (length=6)       1 => int 29   1 =>      array (size=2)       0 => string 'link2' (length=5)       1 => int 75 

for more information can click on link http://php.net/manual/en/function.preg-match-all.php

for $changedstr: let $out output string preg_match_all

$count= 0; foreach($out[0] $result) {  $temp=preg_quote($result[0],'/');  $temp ="/".$temp."/"; $str =preg_replace($temp, "[[".$count."]]", $str,1);   $count++;    } var_dump($str); 

this gives output :

string 'some text [[0]] here [[1]] hahaha' (length=33) 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -