RegEx troubles with converting text to links

I'm trying to make my shoutbox automatically convert posted data into links if it matches certain criteria. It works, except not if there is more than one link in a single shoutbox post.

Here is my code that is meant to convert it:

<? $text = "edit:4961310112967 - edit:021331612649 Are these correct?"; echo $text."<br><br>"; $view = "/(view|edit)\:[0-9]+(\S)?/"; if(preg_match_all($view, $text, $url, PREG_SET_ORDER)) { foreach ($url as $val) { echo "(matched: " . $val[0] . ")\n"; $checkCode = explode(":", $val[0]); if(strcmp($checkCode[0], 'view') == 0) { $text = preg_replace($view, '<a target="_blank" style="text-decoration: underline;color:purple;font-weight:bold;" href="../index.php?UPC='.$checkCode[1].'">(View Product)</a>', $text); } else if(strcmp($checkCode[0], 'edit') == 0) { $text = preg_replace($view, '<a target="_blank" style="text-decoration: underline;color:purple;font-weight:bold;" href="../edit.php?UPC='.$checkCode[1].'">(Edit Product)</a>', $text); } echo "<br>".$text; echo "<br>(".$checkCode[0]." - ".$checkCode[1].")<br><br>"; } } echo "<br><br>".$text."<br><br>"; ?>

As you can see, the $text variable at the top has 2 spots where it says "edit:" - that is what is meant to call the regex to turn it into a link. The link in question would be, for example,

<a href="edit.php?UPC=############"</a>

Currently, how it is, when there is more than one call to the regex, it basically makes both links the first edit:

Sorry, I don't feel like I am explaining this very well.

this string: edit:4961310112967 - edit:021331612649 Are these correct? the regex would make both links edit.php?UPC=4961310112967

-------------Problems Reply------------

I would probably simplify it a bit by dividing it in to 2 regular expressions.

$re = "/edit\\:([0-9]+(\\S)?)/m";
$str = "edit:4961310112967 - edit:021331612649 Are these correct?\n\nedit:1231289389123\n\nedit:123123lkajsdad\n\nview:234234234234234";
$subst = "<a href=\"edit.php?UPC=$1\"</a>";

$result = preg_replace($re, $subst, $str);

and then do the same for view. Hope it helps!

A way that avoids to parse the string several times:

$text = "edit:4961310112967 - edit:021331612649 Are these correct?";

$pattern = '~\b(edit|view):(\d+)~Si';

$links = [
'edit' => ['className' => 'editLink', 'URL' => '../edit.php', 'txt' => '(Edit Product)'],
'view' => ['className' => 'viewLink', 'URL' => '../index.php', 'txt' => '(view Product)']

$result = preg_replace_callback($pattern, function ($m) use ($links) {
$action = strtolower($m[1]);
return '<a class="' . $links[$action]['className']
. '" href="' . $links[$action]['URL'] . '?UPC=' . $m[2]
. '">' . $links[$action]['txt'] . '</a>';
}, $text);

You need to define the two classes editLink and viewLink in your css file.

You probably do not want tot use preg_replace for the string generation, I believe that is mostly the issue at hand. See this example on using sprintf that should behave correctly.

Do you want to following this?

regex : (edit|view)\:([0-9]+)

$re = "/(edit|view)\\:([0-9]+)/m";
$str = "edit:4961310112967 - edit:021331612649 Are these correct?\n\nedit:1231289389123\n\nedit:123123lkajsdad\n\nview:234234234234234";
$subst = "<a href=\"$1.php?UPC=$2\">($1 Product)</a>";

$result = preg_replace($re, $subst, $str);


Category:php Views:7 Time:2019-03-05
Tags: php regex

Related post

  • Converting text to link - php regex issue 2012-02-23

    I'm having a bit of a problem with converting plain text to an url. What I like to have is, if I have text like this:, it's converted to <a href="" target="_blank"></a> I'm kind of a RegEx noob,

  • Convert text url link into clickable link 2014-01-30

    Convert all occurrence of www in string with http://www I have tried Regular expression: /^www(?!http\:\/\/|https\:\/\/)./g; but it's working only in case when any character or digit don't precede www. For example: Find me at in this cas

  • Convert text to links - ignore image src 2012-02-23

    I am using the following function to convert text links to active links: function makeClickableLinks($text) { $text = eregi_replace('(((f|ht){1}tp://)[[email protected]:%_\+.~#?&//=]+)','<a href="\\1">\\1</a>', $text); $text = eregi_replace

  • Compare and save handwritten text with converted text (ink to text) 2013-02-26

    I'd like to know what folks do for this problem: I create handwritten notes on my tablet within ON and then days later convert them to text on my PC. Sometimes I don't have time to correct errors immediately. I also feel it's difficult to correct the

  • Trouble with email, text and receiving or sending in Microsoft Outlook 2012-11-12

    I use Windows Outlook 2003 and I also get my email from an envelope in Dock, using Windows 7, IE 8. This computer is just about 14 mos. old, since I bought it from DELL. Windows 7 Inspiron 580 Everytime they update the print goes back small and I can

  • having trouble with a form and linking data between two tables 2013-06-28

    I am having trouble using a form that records data in two separate tables. One table has basic info on students- basic demographic info and the other table is for Notes/Next Steps. When I record data in the form that goes in the Demographic table it

  • Having trouble with Splitting text 2010-07-16

    Here's the code I'm using : public class splitText { public static void main(String[] args) { String x = "I lost my Phone. I shouldn't drive home alone"; String[] result = x.split("."); for (String i : result) { System.out.println(i); } } } Compiles

  • winForms, help with converting text in txtbox to double if possible? 2010-12-28

    i have the below coding in winForms in 3 different btns. I have very limited knowledge of winForms, as i mostly use Console applications, but i am trying to use text boxes and buttons and user input to create a program that calculates the price varia

  • Having trouble with cURL and expiring links 2011-03-22

    I am working on a page for a library that will display the latest books, movies and items that the library has added to their collection. A friend and I (both of us are new to PHP) have been trying to use cURL to accomplish this. We have gotten the c

  • ÅØÆ - Trouble with the text encoding from HTML -> Java -> MySQL -> Java -> HTML 2011-09-13

    I am currently working on my homepage which is entirely supported by a number of java classes and a MYSQL database. I have a form in HTML where I allow viewers to input a comment. This text is then parsed by a CGI script to the java class where i rea

  • PHP Troubles with converting from JSON to stdClass, making changes, and then converting back to JSON 2012-01-08

    So, in the very beginning, before the send_sms.php is loaded, I have this Json stored in a database: { "chats": { "chat": [{ "id": "1", "name": "Ethan Wilberforce", "messages": { "message": [{ "id": "1", "name": "Ethan Wilberforce", "text": "Hello ho

  • I am having trouble with rich text I cannot change or get adobe flash player installed? newuser also. I want to 2013-10-15

    I am trying to play some games that ask me too install adobe flashplayer still struggling to find the answer reading all kinds of info no use to this rookie thanks --------------Solutions------------- Hi Steven, Thank you for posting your query in Mi

  • Zurb Foundation Top Bar with simple text and links? 2013-10-29

    I'm trying to pull off the following Top Bar with Zurb Foundation. (I'm aware of how to do this with plain HTML...trying to figure out the correct way to do it using Foundation, though.) So you've got the title-area name on the left (which works fine

  • Trouble with changing text on a textbox in vb 2009-07-25

    Hello I am having a problem changing the text color of a textbox in vb I know that changing is like this Textbox.ForeColor = Color.Red when I do this it doesn't change anything still gives me the same black color . Also can it be because it in read o

  • Trouble with converting dec into hex for C 2011-04-17

    Using the following libraries only: #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <math.h> I need a efficient way to convert a decimal to a hex in the f

  • Trouble with GAE/Python Recursive link checking and entry update 2011-11-26

    Assuming I have entries in a datastore that reference other datastore entities: id link val_1 val_2 ----------------------------- 1 None 10 None 2 1 None 4 3 2 None 5 4 3 None 2 etc... etc... etc... etc... I need to recursively progress through the d

  • Having trouble with emails containing a link to connect to 2012-12-20

    When receiving an email with a link to a website such as sears or Kohls or anything else, and I click on it and try to connect to it - it says it is connecting, but nothing happens. Do I need to change some settings in my computer or what do I need t

  • problem with convert text to time in sql server 2008? 2010-01-24

    i have this Ttime as nvarchar(10): "09:52:48" and i have TmpTime as date and i try to convert like this: "UPDATE MEN SET TmpTime = CONVERT(DATETIME, Ttime ,108 )" and i get in TmpTime this: "1900-01-01" why ? thank's in advance --------------Solution

  • Trouble with formating text pasted to Access 2012-11-23

    When I attempt to make spelling corrections or create paragraphs the words combine or cursor moves onto a letter. --------------Solutions------------- When I attempt to make spelling corrections or create paragraphs the words combine or cursor moves

  • Having trouble with unbound text boxes and expressions 2012-12-12

    Hello, I am trying to add a text box to a report that will give me a count of certain fields from my database. In this example, I'm trying to get a count of all the records where in table "Hunting Main" the field "Hunt Area" is equal to "A2" I added

  • I have been having trouble with converting my .WMA files to Itunes and cannot figure why. 2014-04-30

    I switched to my newer computer about a year ago and found my old Ipod, so I decided to download some music to my itunes when I suddenly recalled that I could just transfer all my music from Windows Media Player yet everything comes as a protected fi

  • converted from XP-MSOE to Vista-WinMail successfully 5years ago and now trouble with converting Vista-WinMail to Win7-Outlook 2014-09-16

    How do I recover the folder structure and content, i.e. contacts/email message stores/etc.??? Got the calendar to convert (except reminders), but am now hard stuck. HELP! --------------Solutions------------- MS "service" and Microsoft Community provi

  • Problem with transparent text background in UITableView 2009-12-05

    I've got an annoying problem in my tableview. I was able to achive color-changing cells (blue/white/blue/...), but now I'm in trouble with my text, which has a white background on the blue cells. I've tried for testing to set a background color to re

  • C++ Pointer trouble with File I/O 2010-04-08

    I am writing a function that takes in a output target file and a couple of other arguments. I am currently having trouble with converting types between the argument passed in and using it in the fopen_s() method. FILE* outputf; void myfunc(FILE* fin,

  • Word 2010 - Converting text to table - font type and size change 2014-08-24

    One of our customers is having an issue with converting text to table in Word 2010. The font type and size change whenever this feature is used. How can this be prevented? --------------Solutions------------- Hello Dorilyn, Which font are you using i

Copyright (C), All Rights Reserved.

processed in 0.196 (s). 11 q(s)