Jump to content

preg_replace - referencing the captured text


john mckean

Recommended Posts

I am translating my javascript function to php and am having trouble referencing captured text.

 

Specifically, RegExp.$1 returns the captured text, but ${1} returns empty.

 

I have spent a great deal of time researching this, to no avail.

 

Thanks for any help.

John

 

This loop steps though the text looking for potential linkable URLs or email addresses.  Each match is replaced with a mark <1> .. <5> etc.  A subsequent loop analyzes each capture and replaces the mark with HTML link code or restores the original text.

 

The javascript:

  for (i=0;i<20;i++)
  {
  // Get a potential link and mark where it came from
   $text = $text.replace(/(\S+\.\S+)/,"<"+i+">"); // look for dots that are surrounded by non-whitespace characters
   tlnk[i] = RegExp.$1;
  }

 

My attempted PHP translation:

// Loop through the clear text 
  for ($i=0;$i<20;$i++)
  {
  // Get a potential link and mark where it came from
   $text = preg_replace('(\S+\.\S+)',"<".$i.">",$text,1); // look for dots that are surrounded by non-whitespace characters
   $tlnk[$i] = ${1};
  }

Link to comment
Share on other sites

Thanks for the reply sasa, but preg_match doesn't do the replace. 

 

Is there some way of seeing capture values on a preg_replace

as there is in javascript?

 

OR ...  Can you guide me to a foolproof function that makes links

from text URLs?

 

Thanks,

John

 

 

Link to comment
Share on other sites

try[codeg<?php
function my_link($a = 'i_need_link'){
    static $i = 0, $array = array();
    if($a == 'i_need_link') return $array;
    $i++;
    $array[$i]=  $a[0];
    return "<$i>";
}
$test = 'blah blah www.a.com bla bla blaa b.com aaaa
    sss c.org bla';
$test1 = preg_replace_callback('/\S+\.\S+/', 'my_link', $test);
$links = my_link();
echo $test1,"\n<hr />\n";
print_r($links);
?> 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.