Find next word after colon in regex - php

I am getting a result as a return of a laravel console command like
Some text as: 'Nerad'
Now i tried
$regex = '/(?<=\bSome text as:\s)(?:[\w-]+)/is';
preg_match_all( $regex, $d, $matches );
but its returning empty.
my guess is something is wrong with single quotes, for this i need to change the regex..
Any guess?

Note that you get no match because the ' before Nerad is not matched, nor checked with the lookbehind.
If you need to check the context, but avoid including it into the match, in PHP regex, it can be done with a \K match reset operator:
$regex = '/\bSome text as:\s*'\K[\w-]+/i';
See the regex demo
The output array structure will be cleaner than when using a capturing group and you may check for unknown width context (lookbehind patterns are fixed width in PHP PCRE regex):
$re = '/\bSome text as:\s*\'\K[\w-]+/i';
$str = "Some text as: 'Nerad'";
if (preg_match($re, $str, $match)) {
echo $match[0];
} // => Nerad
See the PHP demo

Just come from the back and capture the word in a group. The Group 1, will have the required string.
/:\s*'(\w+)'$/

Related

Find a pattern in a string

I am trying to detect a string inside the following pattern: [url('example')] in order to replace the value.
I thought of using a regex to get the strings inside the squared brackets and then another to get the text inside the parenthesis but I am not sure if that's the best way to do it.
//detect all strings inside brackets
preg_match_all("/\[([^\]]*)\]/", $text, $matches);
//loop though results to get the string inside the parenthesis
preg_match('#\((.*?)\)#', $match, $matches);
To match the string between the parenthesis, you might use a single pattern to get a match only:
\[url\(\K[^()]+(?=\)])
The pattern matches:
\[url\( Match [url(
\K Clear the current match buffer
[^()]+ Match 1+ chars other than ( and )
(?=\)]) Positive lookahead, assert )] to the right
See a regex demo.
For example
$re = "/\[url\(\K[^()]+(?=\)])/";
$text = "[url('example')]";
if (preg_match($re, $text, $match)) {
var_dump($match[0]);;
}
Output
string(9) "'example'"
Another option could be using a capture group. You can place the ' inside or outside the group to capture the value:
\[url\(([^()]+)\)]
See another regex demo.
For example
$re = "/\[url\(([^()]+)\)]/";
$text = "[url('example')]";
if (preg_match($re, $text, $match)) {
var_dump($match[1]);;
}
Output
string(9) "'example'"

How to hook first hashtaged word in text

I have a PHP $var result named '$caption' result. That result sometimes have #hashtag words like Instagram or Twitter for example;
The Caipirinha is similar to a mojito, except there’s no mint … and there are a lot more limes. #Rio #Olympics #RiodeJaneiro #Caipirinha
I just want hook in text first hastagged word (bold).
In PHP how i can do (hook) first hastagged words in text($var result)?
Thanks for your answers.
You can use preg_match with a regex to match the first #word. Something like:
$string = 'The Caipirinha is similar to a mojito, except there’s no mint … and there are a lot more limes. #Rio #Olympics #RiodeJaneiro #Caipirinha';
preg_match('/#\S+/', $string, $firsthashedword);
echo $firsthashedword[0];
Should do it. \S is any non-whitespace character. The + is a quantifier meaning there must be at least one non-whitespace character after the #. Once it encounters a whitespace the match stops.
PHP Demo: https://eval.in/619122
Regex Demo: https://regex101.com/r/mE8lB6/1
<?php
$result = "This is a sample result #cool #muchwow";
$split = explode("#", $result);
$returnStr = '<b>#'.$split[1].'</b>';
echo str_replace('#'.$split[1], $returnStr, $result);
?>
Output:
This is a sample result <b>#cool</b> #muchwow
Explode will set $split to an array containing the words in between the hashtags.
So in your example the $split variable would equal ['Rio','Olympics'...etc]. Then I find the first occurrence of the '#' which would be equal to $split[1].
After I have that I perform a simple str_replace() to look for the first hashtag adding in html bold tags.
Check it out here: https://eval.in/619127

Check string for defined format and get part of it

How can I check if a string has the format [group|any_title] and give me the title back?
[group|This is] -> This is
[group|just an] -> just an
[group|example] -> example
I would do that with explode and [group| as the delimiter and remove the last ]. If length (of explode) is > 0, then the string has the correct format.
But I think that is not quite a good way, isn't it?
So you want to check if a string matches a regex?
if(preg_match('/^\[group\|(.+)\]$/', $string, $m)) {
$title = $m[1];
}
If the group part is supposed to be dynamic as well:
if(preg_match('/^\[(.+)\|(.+)\]$/', $string, $m)) {
$group = $m[1];
$title = $m[2];
}
Use regular expression matching using PHP function preg_match.
You can use for example regexr.com to create and test a regular expression and when you're done, then implement it in your PHP script (replace the first parameter of preg_match with your regular expression):
$text = '[group|This is]';
// replace "pattern" with regular expression pattern
if (preg_match('/pattern/', $text, $matches)) {
// OK, you have parts of $text in $matches array
}
else {
// $text doesn't contain text in expected format
}
Specific regular expression pattern depends on how strictly you want to check your input string. It can be for example something like /^\[.+\|(.+)\]$/ or /\|([A-Za-z ]+)\]$/. First checks if string starts with [, ends with ] and contains any characters delimited by | in between. Second one just checks if string ends with | followed by upper and lower case alphabetic characters and spaces and finally ].

PHP - regular expression (preg_match)

<?php
$string = "http://example.com/file/D1 http://example.com/file/D2
http://example.com/file/D3";
preg_match_all('/(https?\:\/\/)?(www\.)?example\.com\/file\/(\w+)/i', $string, $matches);
foreach($matches[3] as $value)
{
print $value;
}
?>
I want to preg match the third link and get "D3".
I dont want that it matches with the other two links. This is why it should check if the link has a whitespace at the beginning or the end.
I know that to match with whitespace the expression is \s. I tried but somehow I don't get it. :(
You can add the $ to match the end of the string like this, and it will only return the last one.
preg_match_all('/(https?\:\/\/)?(www\.)?example\.com\/file\/(\w+)$/i', $string, $matches);

PHP regular expression find and append to string

I'm trying to use regular expressions (preg_match and preg_replace) to do the following:
Find a string like this:
{%title=append me to the title%}
Then extract out the title part and the append me to the title part. Which I can then use to perform a str_replace(), etc.
Given that I'm terrible at regular expressions, my code is failing...
preg_match('/\{\%title\=(\w+.)\%\}/', $string, $matches);
What pattern do I need? :/
I think it's because the \w operator doesn't match spaces. Because everything after the equal sign is required to fit in before your closing %, it all has to match whatever is inside those brackets (or else the entire expression fails to match).
This bit of code worked for me:
$str = '{%title=append me to the title%}';
preg_match('/{%title=([\w ]+)%}/', $str, $matches);
print_r($matches);
//gives:
//Array ([0] => {%title=append me to the title%} [1] => append me to the title )
Note that the use of the + (one or more) means that an empty expression, ie. {%title=%} won't match. Depending on what you expect for white space, you might want to use the \s after the \w character class instead of an actual space character. \s will match tabs, newlines, etc.
You can try:
$str = '{%title=append me to the title%}';
// capture the thing between % and = as title
// and between = and % as the other part.
if(preg_match('#{%(\w+)\s*=\s*(.*?)%}#',$str,$matches)) {
$title = $matches[1]; // extract the title.
$append = $matches[2]; // extract the appending part.
}
// find these.
$find = array("/$append/","/$title/");
// replace the found things with these.
$replace = array('IS GOOD','TITLE');
// use preg_replace for replacement.
$str = preg_replace($find,$replace,$str);
var_dump($str);
Output:
string(17) "{%TITLE=IS GOOD%}"
Note:
In your regex: /\{\%title\=(\w+.)\%\}/
There is no need to escape % as its
not a meta char.
There is no need to escape { and }.
These are meta char but only when
used as a quantifier in the form of
{min,max} or {,max} or {min,}
or {num}. So in your case they are treated literally.
Try this:
preg_match('/(title)\=(.*?)([%}])/s', $string, $matches);
The match[1] has your title and match[2] has the other part.

Categories