Replace matching text with href links - php

I have a string like:
#test hello how are you #abcdef
How would I automatically make it so it converts all text that has # to something like:
https://example.com/test
https://example.com/abcdef
I've tried using regex and preg_replace but can't get it down perfectly.

Try regex #(\S+) with substitution https://example.com/$1:
$string = '#test hello how are you #abcdef';
$result = preg_replace('/#(\S+)/', 'https://example.com/$1', $string);
print($result);

Related

PHP replace part of string with link based on pattern

I would like to replace all words starting with 3ABC with an link including the found word. For example:
teststring 3ABCJOEDKLSZ2 teststring hello test
Output would be:
test string <a href='https://google.com/search/3ABCJOEDKLSZ2'>3ABCJOEDKLSZ2</a> teststring hello test
The substring I am looking for is always starting with 3ABC everything after that is dynamic.
You can use php's preg_replace function to match 3ABC followed by 0 or more characters that is not whitespace and then use the match in your code:
$literal = "teststring 3ABCJOEDKLSZ2 teststring hello test";
$formatted = preg_replace("/3ABC\S*/", '\0', $literal);
echo $formatted;
Fiddle: Live Demo
<?php
function makeLink($string)
{
$pattern='/^3ABC[\w\d]+$/';
$url='https://google.com/search/';
$result=preg_replace($pattern, $url.$string ,$string);
return $result;
}
echo makeLink('3ABCHJDGIFD');
?>
Like this?
http://php.net/manual/en/function.preg-replace.php
the pattern will match any digit or word character after 3ABC.

Using preg_replace to transform URLs in a string

I am trying to take a string of HTML and, for all URLs in the string that end in "_page.php" & transform them so that they consist of ONLY the basename and "_page" so for example with this string:
<br/>http://www.website.com/folder/A_page.php TEXT
<br/>http://www.website.com/folder/B_page.php TEXT
<br/>http://www.website.com/folder/C_page.php TEXT
<br/>http://www.website.com/folder/D_dont.php TEXT
I want it to look like:
<br/>A_page TEXT
<br/>B_page TEXT
<br/>C_page TEXT
<br/>http://www.website.com/folder/D_dont.php TEXT
I wrote this:
$str = preg_replace('!(http)(s)?:\/\/[a-zA-Z0-9.?&_/]+_page.php!', '$0',$str);
which gets the right amount of matches, but it is replacing them with $0 which is the entire matched URL so it doesn't change the URLs at all. Doing this:
$str = preg_replace('!(http)(s)?:\/\/[a-zA-Z0-9.?&_/]+_page.php!', '$1',$str);
Gets me:
http TEXT
http TEXT
http TEXT
http://www.website.com/folder/D_dont.php TEXT
So I figured if I switched the $1 to $2 it would return the body of the URL which I could parse and return like this:
$str = preg_replace('!(http)(s)?:\/\/[a-zA-Z0-9.?&_/]+_page.php!', basename('$2','.php'),$str);
$2 turns up empty though. How can I capture the body of the link in preg_replace?
You don't need all those parentheses. For this pattern just use them to capture (/.*_page.php) and that is $1:
$str = preg_replace('!https?:\/\/[a-zA-Z0-9.?&_/]+(/.*_page.php)!', '$1', $str);
To use functions in the replace use a callback. Match the entire URL and then get the basename from that which in this case is $0 or $m[0]:
$str = preg_replace_callback('!https?:\/\/[a-zA-Z0-9.?&_/]+_page.php!',
function($m) { return basename($m[0]); },
$str);

How to replace string with tags used

I want to replace the string "<Reason/>" with empty space or just nothing.
I tried str_replace('<Reason/>','',$string) but it won't take the tags.
I tried str_preg('<Reason/>','', $string) but it leaves the the tags "<>".
I tried str_preg('/^<Reason/>/','', $string) but its gives me exception with unknown modifier '>'.
What can I do to remove the whole string along with tags "<Reason/>"?
You probably forgot to assign the result back to the original variable.
The following code works:
$string = str_replace('<Reason/>','',$string);
Full example:
$string = '<Reason/>lalala<Reason/>';
$string = str_replace('<Reason/>','',$string);
echo $string;
Output
lalala
for Case Insensitive, use
str_ireplace()
instead of `
str_replace()
`

Replace multiple items in a string

i've scraped a html string from a website. In this string it contains multiple strings like color:#0269D2. How can i make str_replace code which replace this string with another color ?
For instance something like this just looping through all color:#0269D in the fulltext string variable?
str_replace("color:#0269D","color:#000000",$fulltext);
you pass array to str_replace function , no need to use loop
$a= array("color:#0269D","color:#000000");
$str= str_replace($a,"", $string);
You have the right syntax. I would add a check:
$newText = str_replace("color:#0269D", "color:#000000", $fulltext, $count);
if($count){
echo "Replaced $count occurrences of 'color'.";
}
This code might be too greedy for what you're looking to do. Careful. Also if the string differs at all, for example color: #0269D, this replacement will not happen.
’str_replace’ already replaces all occurrences of the search string with the replacement string.
If you want to replace all colors but aren't sure which hexcodes you'll find you could use preg_replace to match multiple occurrences of a pattern with a regular expression and replace it.
In your case:
$str = "String with loads of color:#000000";
$pattern = '/color ?: ?#[0-9a-f]{3,6}/i';
$replacement = "color:#FFFFFF";
$result = preg_replace($pattern, $replacement, $str);

Make user name bolded in text in PHP

$text = 'Hello #demo here!';
$pattern = '/#(.*?)[ ]/';
$replacement = '<strong>${1}</strong> ';
echo preg_replace($pattern, $replacement, $text);
This works, I get HTML like this: Hello <strong>demo</strong> here!. But this not works, when that #demo is at the end of string, example: $text = 'Hello #demo';. How can I change my pattern, so it will return same output whenever it is end of the string or not.
Question 2:
What if the string is like $text = 'Hello #demo!';, so it will not put ! as bolded text? Just catch space, end of string or not real-word.
Sorry for bad English, hope you know what I need.
In order to select a word beginning with the # symbol, this regex will work:
$pattern = "/#(\w+)\b/"
`\w` is a short hand character class for `[a-zA-Z0-9_]`. `\b` is an anchor for the beginning or end of a word, in this case the end. So the regex is saying: select something starting with an '#' followed by one or more word characters until the end of the word is reached.
Reference: http://www.regular-expressions.info/tutorial.
You could use a word boundary, that's what they're for:
$pattern = '/#(.+?)\b/';
This will work for question 2 also
You can add an option to match the end of the string:
#(.*?)(?= |\p{P}?$)
Replace with <strong>$1</strong>.
You can also use \p{P} (any Unicode punctuation symbol) to prevent punctuation from bold formatting.
Here is a demo.

Categories