Reputation: 3086
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)";
Upvotes: 0
Views: 80
Reputation: 42048
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;
Upvotes: 4
Reputation: 8105
preg_replace('/@\[([^\]]+)\]\((\w+):(\d+)\)/', '<a href="link/$2/$3">$1</a>', $text);
Upvotes: 1
Reputation: 370
\@\[.*?\]\(.*?\)
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:
\@\[.*\]\(.*\)
Upvotes: 0
Reputation: 91734
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
Upvotes: 0