PHP replace part of string with link based on pattern - php

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.

Related

Replace all occurrences using preg_replace

The code below works perfectly:
$string = '(test1)';
$new = preg_replace('/^\(+.+\)+$/','word',$string);
echo $new;
Output:
word
If the code is this:
$string = '(test1) (test2) (test3)';
How to generate output:
word word word?
Why my regex do not work ?
^ and $ are anchors which means match should start from start of string and expand upto end of string
. means match anything except newline, + means one or more, by default regex is greedy in nature so it tries to match as much as possible where as we want to match ( ) so we need to change the pattern a bit
You can use
\([^)]+\)
$string = '(test1) (test2) (test3)';
$new = preg_replace('/\([^)]+\)/','word',$string);
echo $new;
Regex Demo

Regular Expression That Contains At Least One Of Each

I'm trying to capitalize "words" that have at least one number, letter, and special character such as a period or dash.
Things like: 3370.01b, 6510.01.b, m-5510.30, and drm-2013-c-004914.
I don't want it to match things like: hello, sk8, and mixed-up
I'm trying to use lookaheads, as suggested, but I can't get it to match anything.
$output = preg_replace_callback('/\b(?=.*[0-9]+)(?=.*[a-z]+)(?=.*[\.-]+)\b/i', function($matches){return strtoupper($matches[0]);}, $input);
You can use this regex to match the strings you want,
(?=\S*[a-z])(?=\S*\d)[a-z\d]+(?:[.-][a-z\d]+)+
Explanation:
(?=\S*[a-z]) - This look ahead ensures that there is at least an alphabet character in the incoming word
(?=\S*\d) - This look ahead ensures that there is at least a digit in the incoming word
[a-z\d]+(?:[.-][a-z\d]+)+ - This part captures a word contain alphanumeric word containing at least one special character . or -
Online Demo
Here is the PHP code demo modifying your code,
$input = '3370.01b, 6510.01.b, m-5510.30, and drm-2013-c-004914 hello, sk8, and mixed-up';
$output = preg_replace_callback('/(?=\S*[a-z])(?=\S*\d)[a-z\d]+(?:[.-][a-z\d]+)+/i', function($matches){return strtoupper($matches[0]);}, $input);
echo $output;
Prints,
3370.01B, 6510.01.B, M-5510.30, and DRM-2013-C-004914 hello, sk8, and mixed-up
Regular expression:
https://regex101.com/r/sdmlL8/1
(?=.*\d)(.*)([-.])(.*)
PHP code:
https://ideone.com/qEBZQc
$input = '3370.01b';
$output = preg_replace_callback('/(?=.*\d)(.*)([-.])(.*)/i', function($matches){return strtoupper($matches[0]);}, $input);
I don't think you never captured anything to put into matches...
$input = '3370.01b foo';
$output = preg_replace_callback('/(?=.*[0-9])(?=.*[a-z])(\w+(?:[-.]\w+)+)/i', function($matches){return strtoupper($matches[0]);}, $input);
echo $output;
Output
3370.01B foo
Sandbox
https://regex101.com/r/syJWMN/1

Twitter handle regular expression PHP [duplicate]

i'm not very firm with regular Expressions, so i have to ask you:
How to find out with PHP if a string contains a word starting with # ??
e.g. i have a string like "This is for #codeworxx" ???
I'm so sorry, but i have NO starting point for that :(
Hope you can help.
Thanks,
Sascha
okay thanks for the results - but i did a mistake - how to implement in eregi_replace ???
$text = eregi_replace('/\B#[^\B]+/','\\1', $text);
does not work??!?
why? do i not have to enter the same expression as pattern?
Match anything with has some whitespace in front of a # followed by something else than whitespace:
$ cat 1812901.php
<?php
echo preg_match("/\B#[^\B]+/", "This should #match it");
echo preg_match("/\B#[^\B]+/", "This should not# match");
echo preg_match("/\B#[^\B]+/", "This should match nothing and return 0");
echo "\n";
?>
$ php 1812901.php
100
break your string up like this:
$string = 'simple sentence with five words';
$words = explode(' ', $string );
Then you can loop trough the array and check if the first character of each word equals "#":
if ($stringInTheArray[0] == "#")
Assuming you define a word a sequence of letters with no white spaces between them, then this should be a good starting point for you:
$subject = "This is for #codeworxx";
$pattern = '/\s*#(.+?)\s/';
preg_match($pattern, $subject, $matches);
print_r($matches);
Explanation:
\s*#(.+?)\s - look for anything starting with #, group all the following letters, numbers, and anything which is not a whitespace (space, tab, newline), till the closest whitespace.
See the output of the $matches array for accessing the inner groups and the regex results.
#OP, no need regex. Just PHP string methods
$mystr='This is for #codeworxx';
$str = explode(" ",$mystr);
foreach($str as $k=>$word){
if(substr($word,0,1)=="#"){
print $word;
}
}
Just incase this is helpful to someone in the future
/((?<!\S)#\w+(?!\S))/
This will match any word containing alphanumeric characters, starting with "#." It will not match words with "#" anywhere but the start of the word.
Matching cases:
#username
foo #username bar
foo #username1 bar #username2
Failing cases:
foo#username
#username$
##username

Find a pattern within' long string

I have a question with some patterns I'm trying to do... this is the code I have:
$test = 'this is a simply test';
preg_match_all("/^this is a [a-zA-Z] test$/", $test, $op_string);
print_r($op_string);
I've been trying for this guys, but this doesn't works properly. This should output: simply
The pattern must contains same as $test (the string I mean... it can't contain only [a-zA-Z] because we'll need to find it more exactly as possible).
Thank you so much!
Use quantifier + to match 1 or more letters:
$test = 'this is a simply test';
preg_match_all('/^this is a [a-zA-Z]+ test$/', $test, $op_string);
You're using [a-zA-Z] which will only match a single letter.
try this:
$re = "/^this is a ([a-zA-Z\\s]+) test$/m";
$str = "this is a simply test";
preg_match_all($re, $str, $matches);
var_dump($matches[1]); // here you get match word or word set
live demo
output:
array (size=1)
0 => string 'simply' (length=6)

preg_match all words start with an #?

i'm not very firm with regular Expressions, so i have to ask you:
How to find out with PHP if a string contains a word starting with # ??
e.g. i have a string like "This is for #codeworxx" ???
I'm so sorry, but i have NO starting point for that :(
Hope you can help.
Thanks,
Sascha
okay thanks for the results - but i did a mistake - how to implement in eregi_replace ???
$text = eregi_replace('/\B#[^\B]+/','\\1', $text);
does not work??!?
why? do i not have to enter the same expression as pattern?
Match anything with has some whitespace in front of a # followed by something else than whitespace:
$ cat 1812901.php
<?php
echo preg_match("/\B#[^\B]+/", "This should #match it");
echo preg_match("/\B#[^\B]+/", "This should not# match");
echo preg_match("/\B#[^\B]+/", "This should match nothing and return 0");
echo "\n";
?>
$ php 1812901.php
100
break your string up like this:
$string = 'simple sentence with five words';
$words = explode(' ', $string );
Then you can loop trough the array and check if the first character of each word equals "#":
if ($stringInTheArray[0] == "#")
Assuming you define a word a sequence of letters with no white spaces between them, then this should be a good starting point for you:
$subject = "This is for #codeworxx";
$pattern = '/\s*#(.+?)\s/';
preg_match($pattern, $subject, $matches);
print_r($matches);
Explanation:
\s*#(.+?)\s - look for anything starting with #, group all the following letters, numbers, and anything which is not a whitespace (space, tab, newline), till the closest whitespace.
See the output of the $matches array for accessing the inner groups and the regex results.
#OP, no need regex. Just PHP string methods
$mystr='This is for #codeworxx';
$str = explode(" ",$mystr);
foreach($str as $k=>$word){
if(substr($word,0,1)=="#"){
print $word;
}
}
Just incase this is helpful to someone in the future
/((?<!\S)#\w+(?!\S))/
This will match any word containing alphanumeric characters, starting with "#." It will not match words with "#" anywhere but the start of the word.
Matching cases:
#username
foo #username bar
foo #username1 bar #username2
Failing cases:
foo#username
#username$
##username

Categories