1

I have the following string...

Out with the <_link>user://1|Team GB  for
<_link>tag://FridayBeers|#FridayBeers

And I have written the following regex which strips out the tags and characters.

~<(/){0,1}.*?( /){0,1}>|(tag://\w*\||user://[0-9]*\|)~

However what I now need to achieve is the following

<_link>user://1|Team GB gets converted to <a href="user/1">Team GB</a> and for <_link>tag://FridayBeers|#FridayBeers to <a href="tags/FridayBeers">#FridayBeers</a>

Can some post an answer that changes my regex to allow for this I am using PHP;

$post_text = "Out with the <_link>user://1|Team GB  for <_link>tag://FridayBeers|#FridayBeers";
$pattern = "~<(/){0,1}.*?( /){0,1}>|(tag://\w*\||user://[0-9]*\|)~"; //"~<(/){0,1}.*?( /){0,1}>|(tag://\w*\||user://[0-9]\|)~";
$replacement = " ";
$regexd = preg_replace($pattern, $replacement, $post_text);
2
  • You should probably have a look at preg_replace_callback Commented Feb 9, 2014 at 14:55
  • @kelunik thanks for the tip, could you post an answer with a code sample showing how you would do this, I appreciate it Commented Feb 9, 2014 at 15:04

2 Answers 2

1

You can achieve this using preg_replace_callback. The following code sample is just a minimal sample (see notice below).

<?php

$pattern = "~\<_link\>((?<typeUser>user)\://(?<userId>\d+)\|(?<userName>[a-zA-Z]+)|(?<typeTag>tag)\://(?<tagLink>[a-zA-Z]+)\|#(?<tagTitle>[a-zA-Z]+))~";
$string = "<_link>user://1|Team GB and <_link>tag://FridayBeers|#FridayBeers";

echo preg_replace_callback($pattern, function($match) {
    if(!empty($match['typeUser'])) {
        return '<a href="user/'.$match['userId'].'">'.$match['userName'].'</a>';
    } else {
        return '<a href="tags/'.$match['tagLink'].'">'.$match['tagTitle'].'</a>';
    }
}, $string);

This code doesn't care about escaping HTML. Additionally the pattern only cares about names without spaces.

Sign up to request clarification or add additional context in comments.

3 Comments

That seems to work well and thank you however some of the names as per the example have spaces in them for example my name Justin Erswell anyway of dealing with that?
You need something to make clear there's the end of the name. Imagine the following input: <_link>user://1|Team GB was the ... team. Should was stick to the name or not? How should your script know?
You are right of course this is a little tricky unfortunately I am stuck with the data. Thanks for your help!
1

Consider this preg_replace code:

$s = '<_link>tag://FridayBeers|#FridayBeers';
$r = preg_replace('~<_link>([^:]+)://([^|]+)\|([\w -]+)~', '<a href="$1/$2">$3</a>', $s);
//=> <a href="tag/FridayBeers">#FridayBeers</a>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.