How to parse text, identify URL and append word at end?

Discussion in 'PHP' started by it career, Nov 13, 2013.

  1. #1
    Hi PHPers,
    Suppose I have got a text file which contains text like
    
    Welcome
    some text http://example.com/sdsada/ some text
    Some more words
    Some text http://example.com/sdsada/asdsads some text
    ..
    ..
    ..
    
    Code (markup):
    I want to read this file in php and convert it automatically to something like
    
    Welcome
    some text <a href="http://example.com/sdsada/mytext">http://example.com/sdsada/</a> some text
    Some more words
    Some text <a href="http://example.com/sdsada/asdsads/mytext">http://example.com/sdsada/asdsads/</a> some text
    ..
    ..
    ..
    
    Code (markup):
    Your help is much appreciated.
     
    it career, Nov 13, 2013 IP
  2. Vooler

    Vooler Well-Known Member

    Messages:
    1,146
    Likes Received:
    64
    Best Answers:
    4
    Trophy Points:
    150
    #2
    That is easy:

    <?php
    $filename = 'test.txt';
    $outputfile = 'newfile.txt';
    $data = file_get_contents($filename);
    $data =
    preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@','<a href="$1" target="_blank">$1</a>', $data);
    file_put_contents($outputfile, $data);
    PHP:
     
    Vooler, Nov 13, 2013 IP
  3. kutchbhi

    kutchbhi Active Member

    Messages:
    130
    Likes Received:
    4
    Best Answers:
    2
    Trophy Points:
    70
    #3
    possible non-regex solution:
    1. explode it
    2. run each word through a FILTER (URL or something)
    3. if it is a URL simply append a tag
     
    kutchbhi, Nov 16, 2013 IP
  4. ezprint2008

    ezprint2008 Well-Known Member

    Messages:
    611
    Likes Received:
    15
    Best Answers:
    2
    Trophy Points:
    140
    Digital Goods:
    1
    #4
    will the 'some text' before the href always be the same?
    if so you could do string replace ..to replace the 'some text' and white space with the new formatting.
    simple fix
     
    ezprint2008, Nov 16, 2013 IP