1

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!

3
  • space, any size number & then space - is that correct? Commented Mar 25, 2012 at 21:45
  • @Dagon Yes, that's correct. :) Commented Mar 25, 2012 at 21:46
  • Do you want it to also replace 3 and 4 in the following, or should those be excluded? 1& in the beginning. 2& in the middle. 3&followed by a word. And4& preceded by a word. Finally ending with a 5&? Commented Mar 25, 2012 at 22:05

3 Answers 3

2
$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)
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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);

1 Comment

I expanded my answer: it uses preg_replace

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.