0

I am looking to use regex in PHP to replace instances of @[SOME TEXT](id:1) to <a href="link/$id">SOME TEXT</a>

I have been trying various regex tutorials online but cannot figure it out. This is what I have so far \@\[.*\] but it selects all from @[Mr to then end Kenneth]

$text = "This is the thing @[Mr Hugh Warner](id:1) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae minima mollitia, sit porro eius similique fugit quis fugiat quae perferendis excepturi nam in deserunt natus eaque magni soluta esse rem. @[Kenneth Auchenberg](contact:1) Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae minima mollitia, sit porro eius similique fugit quis fugiat quae perferendis excepturi nam in deserunt natus eaque magni soluta esse rem. @[Kenneth](id:7)";

4 Answers 4

4

You can use a regex like this:

/@\[([^\]]+)\]\(id:(\d+)\)/

PHP code:

$pattern = '/@\[([^\]]+)\]\(id:(\d+)\)/';
$replacement = '<a href="link/$2">$1</a>';
$text = preg_replace($pattern, $replacement, $text);

echo $text;
Sign up to request clarification or add additional context in comments.

Comments

1
preg_replace('/@\[([^\]]+)\]\((\w+):(\d+)\)/', '<a href="link/$2/$3">$1</a>', $text);

2 Comments

Is it possible to get the preg_replace to output this '<a href="link/id/$2">$1</a>' instead of $1, $2, $3? Id / contact will always be id in the system
What do you mean? What is the difference between (id:1) and (contact:7), and what other words (other than "id" and "contact") could be there? How should they be replaced?
0

You want lazy instead of greedy matching in the example that you tried:

\@\[.*?\]
      ^ make it lazy

Another option would be to make sure you don't match any closing blockquote:

\@\[[^\]]+\]
    ^^^^^ a character class containing any character except the ] character

2 Comments

Ah yes make stuff inside stuff optional. You say lazy. Is that a bad thing?
@PierceMcGeough No, that's just what it's called: Match as few characters as possible to meet the condition instead of as many as possible. Note that it has nothing to do with optional, the ? symbol has a different meaning here. See for example regular-expressions.info/repeat.html
0
\@\[.*?\]\(.*?\)

This will save is as:

Array
(
    [0] => @[Mr Hugh Warner](id:1)
)

I used this site for help: http://www.phpliveregex.com/p/7sv

Also, This doesn't have to be lazy...this works exactly the same as above:

\@\[.*\]\(.*\)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.