Search code examples
phphtmlxhtmlmailto

How would I make the first word of a string a mailto link to the last?


I have a program that is reading in lines from a text file, and each line is formatted like this.

House 5682 Rose Road [email protected]

I want my program to print out each line where the word 'house' is a mailto link to the email, and the email is not printed. Right now I have it printing each line and cutting out the email, but I can't figure out how to do the mailto link. I need it to come out like this:

House 5682 Rose Road 

With 'House' mailto linked to [email protected]. This is what I have so far.

$houses = file('houseList.txt');
$houseNumber = 1;
foreach($houses as $house)
{
  $line = preg_replace('/\W\w+\s*(\W*)$/', '$1', $house);
  echo " ".$houseNumber." ";
  echo substr($line,0,strrpos($house, ' '))."\n";
  $houseNumber++;
}

Solution

  • this should do it. the whole line, minus the email address, is the link. easy to modify if you just want house to be the anchor.

    $houses = file('houseList.txt');
    $houseNumber = 1;
    foreach($houses as $house)
    {
      $pos    = strrpos($house," ");
      $mailto = substr($house, $pos+1);
      $house  = substr($house, 0, $pos);
    
      echo "<a href=mailto:$mailto>$house</a><br>";
      $houseNumber++;
    }