Reputation: 3057
I'm working on a replying system similar to twitters.
In a string there is a piece of text where the id is variable ex.: 14&
, 138&
depending to who you're replying.
How can I find the 14&
in a string and replace it with <u>14&</u>
?
This is how it looks:
14& this is a reply to the comment with id 14
This is how it should look like:
<u>14&</u> this is a reply to the comment with id 14
How can I do this in PHP? Thanks in advance!
Upvotes: 1
Views: 273
Reputation: 11859
If you know the ID, it's simple:
<?php
$tweet_id = '14';
$replaced = str_replace("{$tweet_id}&", "<u>{$tweet_id.}&</u>", $original);
If you don't, preg_replace
<?php
//look for 1+ decimals (0-9) ending with '$' and replaced it with
//original wrapped in <u>
$replaced = preg_replace('/(\d+&)/', '<u>$1</u>', $original);
Upvotes: 2
Reputation: 4042
$text = "14& this is a reply to the comment with id 14";
var_dump(preg_replace("~\d+&~", '<u>$0</u>', $text));
outputs:
string '<u>14&</u> this is a reply to the comment with id 14' (length=52)
To get rid of the &
:
preg_replace("~(\d+)&~", '<u>$1</u>', $text)
outputs:
string '<u>14</u> this is a reply to the comment with id 14' (length=51)
$0
or $1
will be the your id. You can replace the markup with anything you like.
for instance a link:
$text = "14& is a reply to the comment with id 14";
var_dump(preg_replace("~(\d+)&~", '<a href="#comment$1">this</a>', $text));
outputs:
string '<a href="#comment14">this</a> is a reply to the comment with id 14' (length=66)
Upvotes: 2
Reputation: 766
Use regular expressions with the preg_replace function.
<?php
$str = '14& this is a reply to the comment with id 14';
echo preg_replace('(\d+&)', '<u>$0</u>', $str);
The regex matches: one or more digits followed by an ampersand.
Upvotes: 2