icc
icc

Reputation: 13

How to create hyperlink after finding the words from text file

I have a text file containing links and the website names.

For example:

Yahoo http://www.yahoo.com
Google http://www.google.com

then i have to load this text file into my php website. I can load the file

then I have to convert this texts into hyperlink. I have to find the links' position.

I have used:

echo strchr("$array[$x]","http") // find the hyperlink
echo substr("$array[$x]",0,8) // find the website name

After finding the websites' names and their hyperlinks how can I use <a href ...></a> to create links?

I tried:

echo "<a href = "echo strchr("$array[$x]","http");>echo substr("$array[$x]",0,8). "<br>\n"; </a>

But it doesn't work. I don't know how to do it in fact. Can anyone here help me to fix it?


Here are my sample codes:

s13.postimg.org/ce8omobnr/image.png

s23.postimg.org/ym3nifyfv/image.png

Upvotes: 1

Views: 1001

Answers (2)

kraysak
kraysak

Reputation: 1756

    $file1 = "test.txt";
    $lines = file($file1);
    foreach($lines as $line_num => $line)
    {
    //echo $line;
    $piece=explode(' ',$line);
    //echo $piece[0]."<br>";
    //echo $piece[1];
    echo '<a href="'.$piece[1].'">'.$piece[0].'</a><br>';
    }

the file "test.txt":

Yahoo http://www.yahoo.com
Google http://www.google.com

EDIT

so, a litle update:

$file1 = "updir/bookmark.txt";
$lines = file($file1);
foreach($lines as $line)
{
    $piece=explode(" ",$line);
    $link=trim($piece[1]);
    $text=trim($piece[0]);
    echo '<a href="'.$link.'">'.$text.'</a><br>';
}

Upvotes: 1

Ruben
Ruben

Reputation: 5095

Not sure why you don't just use explode to split up the pieces of each line in the input file, unless the format of the input is different from what you showed.

Otherwise you can use file() to read in the input file, which returns an array of lines in the file. Then you can loop through this array and explode every line into two pieces. The first piece is the name, the second the hyperlink. Then just create the link tag and you're all set.

Example code:

<?php
$lines = file('input.txt');

foreach ($lines as $curLine)
{
    $pieces = explode(" ", $curLine, 2);

    echo sprintf("<a href=\"%s\">%s</a>\n", trim($pieces[1]), trim($pieces[0]));
}

Edit: Just saw your update and noticed you have multiple spaces or other whitespace characters between the tokens on each line. In that case replace the line:

$pieces = explode(" ", $curLine, 2);

with:

$pieces = preg_split('/\s+/', $curLine);

Edit 2: If the actual separator between the label and hyperlink on each line is one or multiple tabs and the labels may contain spaces (see Fred's comment below) then change the line into:

$pieces = preg_split('/\t+/', $curLine);

This will prevent the preg_split from splitting the labels containing spaces.

Upvotes: 1

Related Questions