php find # in string with regex - php

I have a php variable where I need to show #value Values as link pattern.
The code looks like this.
$reg_exUrl = "/\#::(.*?)/";
// The Text you want to filter for urls
$text = "This is a #simple text from which we have to perform #regex operation";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, ''.$url[0].'', $text);
} else {
// if no urls in the text just return the text
echo "IN Else #$".$text;
}

By using \w, you can match a word contains alphanumeric characters and underscore. Change your expression with this:
$reg_exUrl = "/#(.*?)\w+/"

$reg_exUrl = "/\#::(.*?)/";
This doesn't match because of the following reasons
1. there is no need to escape #, this is because it is not a special character.
2. since you want to match just # followed by some words, there is no need for ::
3. (.*?) tries to match the least possible word because of the quantifier ?. So it won't match the required length of word you need.
If you still want to go by your pattern, you can modify it to
$reg_exUrl = "/#(.*?)\w+/" See demo
But a more efficient one that still works is
$reg_exUrl = "/#\w+/". see demo

It's not clear to me exactly what you need match. If you want to replace a # followed by any word chars:
$text = "This is a #simple text from which we have to perform #regex operation";
$reg_exUrl = "/#(\w+)/";
echo preg_replace($reg_exUrl, '$1', $text);
//Output:
//This is a simple text from which we have to perform regex operation
The replacement uses $0 to refer to the text matched and $1 the first group.

Related

Target message to match with regex

I have to check csv files live and match some expression to get data.
These files can have different type of message so different matching expression.
The message can be something like that
GuiPrinter.ProcessPrint of 116806 25374 K356 S Black Face.png 229 at 1
table
And I want to get 116806 25374 K356 S Black Face.png
. So the regex associate to this kind of file would be something like (GuiPrinter.ProcessPrint of )(.*)([.][png|jpg|jpeg|PNG|JPG|JPEG]*) and I can return $result[2]
But the message and the regex can change, so I need a common function that can return the string that I want based on the regex, the function would have message and regex parameters. Maybe for another file the string that I want would be on first position so my $result[2] won't work.
How can I ensure to always return the string that I want to match ?
Use
\preg_match('/GuiPrinter.ProcessPrint of(.*?)\.(gif|png|bmp|jpe?g)/', $str, $match);
print_r($match[1]);
You could match the text GuiPrinter.ProcessPrint and then use \K to reset the starting point of the reported match.
Match any character zero or more times non greedy .*?, then match a dot \. and any of the image extensions in a non capturing group (?:gif|png|bmp|jpe?g) followed by a word boundary \b
GuiPrinter\.ProcessPrint of \K.*?\.(?:gif|png|bmp|jpe?g)\b
Note that to match the dot literally you have to escape it \.
For example to return 1 match using preg_match:
$str = 'GuiPrinter.ProcessPrint of 116806 25374 K356 S Black Face.png 229 at 1 table';
$re = '/GuiPrinter\.ProcessPrint of \K.*?\.(?:gif|png|bmp|jpe?g)\b/';
function findMatch($message, $regex) {
preg_match($regex, $message, $matches);
return array_shift($matches);
}
$result = findMatch($str, $re);
if ($result) {
echo "Found: $result";
} else {
echo "No match.";
}
Demo

Php select from string

Hi I'm new to php and I need a little help
I need to change the text that is between ** in php string and put it between html tag
$text = "this is an *example*";
But I really don't know how and i need help
personally I would use explode, you can then piece the sentence back together if the example appears in the middle of a sentence
<?php
$text = "this is an *example*";
$pieces = explode("*", $text);
echo $pieces[0];
?>
Edit:
Since you're looking for what basically amounts to custom BB Code use this
$text = "this is an *example*";
$find = '~[\*](.*?)[\*]~s';
$replace = '<span style="color: green">$1</span>';
echo preg_replace($find,$replace,$text);
You can add this to a function and have it parse any text that gets passed to it, you can also make the find and replace variables into arrays and add more codes to it
You really should use a DOM parser for things like this, but if you can guaratee it will always be the * character you can use some regex:
$text = "this is an *example*";
$regex = '/(?<=\*)(.*?)(?=\*)/';
$replacement = 'ostrich';
$new_text = preg_replace($regex, $replacement, $text);
echo $new_text;
Returns
this is an *ostrich*
Here is how the regex works:
Positive Lookbehind (?<=\*)
\* matches the character * literally (case sensitive)
1st Capturing Group (.*?)
.*? matches any character (except for line terminators)
*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
Positive Lookahead (?=\*)
\* matches the character * literally (case sensitive)
This regex essentially starts and ends by looking at what is ahead of and behind the search character you specified and leaves those characters intact during the replacement with preg_replace().

PHP Find All Hashtags But No In Link

i need to find all hashtags in string but not on link example:
#q https://www.youtube.com/watch?v=#Vmyx7cyZcKU #q1 #q3 [ I Want to Get only #q, #q1, #q not hashtags in link ]
my code:
$string = "#q https://www.youtube.com/watch?v=#Vmyx7cyZcKU #q1 #q3";
// Link
$string = preg_replace("!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9#:%_+.~#?&;//=]+)!i", "<a href='$1' target='_blank'>$1</a>", $string);
// Hashtag
$hashtag_url = $web_url. "hashtag/\\0";
$string = preg_replace("(\s?#\w+)", "<a href='$hashtag_url'>\\0</a>", $string);
See Image What My Code Show !!!
http://i.stack.imgur.com/p8IyE.png
Match all the hashtags outside the URL can be achieved with a regex that matches URLs and discards them, and then matches hastags in all other contexts:
'~(?:f|ht)tps?://[-a-zA-Zа-яА-Я()0-9#:%_+.\~#?&;/=]+(*SKIP)(*F)|#(\w+)~'
See the regex demo
PHP demo:
$string = "#q https://www.youtube.com/watch?v=#Vmyx7cyZcKU #q1 #q3";
$string = preg_replace("!(?:f|ht)tps?://[-a-zA-Zа-яА-Я()0-9#:%_+.~#?&;/=]+(*SKIP)(*F)|#(\w+)!", "<a href='$1'>$0</a>", $string);
echo $string;
Feel free to adjust (especially the replacement pattern) as per your needs.
Details:
(?:f|ht)tps?://[-a-zA-Zа-яА-Я()0-9#:%_+.\~#?&;/=]+ - the URL matching part (taken from your code)
(*SKIP)(*F) - PCRE verbs omitting the match and proceeding to the next match from the current index
| - or
#(\w+) - a # followed with 1 or more word chars.
To enable \w to match Unicode letters, too, add ~u modifier at the end.

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.

preg_replace() seems to remove entire word instead of part of it

I'm trying to match a certain word and replace part of the word with certain text but leave the rest of the word intact. It is my understanding that adding parentheses to part of the regex pattern means that the pattern match within the parentheses gets replaced when you use preg_replace()
for testing purposes I used:
$text = 'batman';
echo $new_text = preg_replace('#(bat)man#', 'aqua', $text);
I only want 'bat' to be replaced by 'aqua' to get 'aquaman'. Instead, $new_text echoes 'aqua', leaving out the 'man' part.
preg_replace replaces all the string matched by regular expression
$text = 'batman';
echo $new_text = preg_replace('#bat(man)#', 'aqua\\1', $text);
Capture man instead and append it to your aqua prefix
Another way of doing that is to use assertions:
$text = 'batman';
echo $new_text = preg_replace('#bat(?=man)#', 'aqua', $text);
I would not use preg_* functions for this and just do str_replace() DOCs:
echo str_replace('batman', 'aquaman', $text);
This is simpler as a regex is not really needed in this case. Otherwise it would be with a regular expression:
echo $new_text = preg_replace('#bat(man)#', 'aqua\\1', $text);
This will substitute your man in after aqua when replacing the entire search phrase. preg_replace DOCs replaces the entire matching portion of the pattern.
The way you're trying to do it, it would be more like:
preg_replace('#bat(man)#', 'aqua$1', $text);
I'd using positive lookahead:
preg_replace('/bat(?=man)/', 'aqua', $text)
Demo here: http://ideone.com/G9F4q
The brackets are creating a capturing group, that means you can access the part matched by this group using \1.
you can do either what zerkms suggested or use a lookahead that does just check but not match.
$text = 'batman';
echo $new_text = preg_replace('#bat(?=man)#', 'aqua', $text);
This will match "bat" but only if it is followed by "man", and only "bat" is replaced.

Categories