[prev in list] [next in list] [prev in thread] [next in thread] 

List:       php-general
Subject:    Re: [PHP] preg_replace question
From:       Alex Nikitin <niksoft () gmail ! com>
Date:       2011-01-25 15:06:15
Message-ID: AANLkTikyYPhjSv2MoXPVa6=BVacr8qZ0bER+B=JhK7X4 () mail ! gmail ! com
[Download RAW message or body]


$internal_links=array();

I prefer to init arrays, it also avoids unnecessary notices, and sometimes
weird results, but either one of those while loops should make the desired
array

while($row = mysql_fetch_array($result, MYSQL_ASSOC))
 { array_push($internal_links, array('phrase'=>$row['phrase'],
'link'=>$row['link'])); }
or

while($row = mysql_fetch_array($result, MYSQL_ASSOC))  { $internal_links[] =
array('phrase'=>$row['phrase'], 'link'=>$row['link']); }

or

while($row = mysql_fetch_object($result))  { $internal_links[] =
array('phrase'=>$row->phrase,
'link'=>$row->link); }

(you can figure out how to do it with array_push if you choose to, but you
get the general idea)


~ Alex

On Jan 25, 2011 6:35 AM, "Merlin Morgenstern" <merlin_x@fastmail.fm> wrote:
> Am 24.01.2011 18:08, schrieb Alex Nikitin:
>> If you declare your arrays, and set k to 0 first, put quotes around array
>> values and use the correct limit (you can default to -1), you will get
>> results, here is code and example (hopefully this helps you)
>>
>>
>> <?php
>> function internal_links($str, $links, $limit=-1) {
>> $pattern=array();
>> $replace=array();
>> $k=0;
>> foreach($links AS $link){
>> $pattern[$k] = "~\b({$link['phrase']})\b~i";
>> $replace[$k] = '<a href="'.$link['link'].'">\\1</a>';
>> $k++;
>> }
>> return preg_replace($pattern,$replace,$str, $limit);
>> }
>>
>> echo internal_links("süße knuffige Beagle Welpen ab sofort",
>> array(array('phrase'=>"beagle",
>> 'link'=>"http://google.com"),array('phrase'=>"welpen",
>> 'link'=>"http://wolframalpha.com")), -1);
>>
>> Output:
>> süße knuffige<a href="http://google.com">Beagle</a> <a href="
>> http://wolframalpha.com">Welpen</a> ab
>>
>> ~Alex
>>
>
> Hello,
>
> thank you all for your help. It seems that I am building the array
> wrong. Your code works with that array:
>
> $internal_links = array(array('phrase'=>"beagle",
> 'link'=>"http://google.com"),array('phrase'=>"welpen",
> 'link'=>"http://wolframalpha.com"));
>
> I am pulling the data out of a DB and am using this code:
> while ($row = mysql_fetch_object($result)){
> $internal_links[$row->ID]['phrase'] = $row->phrase;
> $internal_links[$row->ID]['link'] = $row->link;
> }
>
> You build the array different, could you help me to adapt this on my
> code? I tried $internal_links['phrase'][] as well, but that did not help
> either.
>
> Thank you for any help,
>
> Merlin
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic