preg_match start and end of string and replace - php

Could someone help with a preg_match expression I need it to match the - dash character at the start and end of a string. This is for tags e.g. match -my-tag- should then be my-tag so It only matches the start and end of a string and replace it the characters with and empty string

You can do that with this easy expression:
$string = "-my-tag-";
$tag = preg_replace("/^-(.*)-$/", "$1", $string);
^ and $ are used to match the start and the end of the string, while (.*) captures every other symbols.
You can read more about regular expressions in the official PHP Documentation.

Related

PHP regular expression start and end with given strings

I have a string like this
05/15/2015 09:19 PM pt_Product2017.9.abc.swl.px64_kor_7700 I need to select the pt_Product2017.9.abc.swl.px64_kor from that. (start with pt_ and end with _kor)
$str = "05/15/2015 09:19 PM pt_Product2017.9.abc.swl.px64_kor_7700";
preg_match('/^pt_*_kor$/',$str, $matches);
But it doesn't work.
You need to remove the anchors, adda \b at the beginning to match pt_ preceded with a non-word character, and use a \S with * (\S shorthand character class that matches any character but whitespace):
preg_match('/\bpt_\S*_kor/',$str, $matches);
See regex demo
In your regex,^ and $ force the regex engine to search for the ptat the beginning and _kor at the end of the string, and _* matches 0 or more underscores. Note that regex patterns are not the same as wildcards.
In case there can be whitespace between pt_ and _kor, use .*:
preg_match('/\bpt_.*_kor/',$str, $matches);
I should also mention greediness: if you have pt_something_kor_more_kor, the .*/\S* will match the whole string, but .*?/\S*? will match just pt_something_kor. Please adjust according to your requirements.
^ and $ are the start and end of the complete string, not only the matched one. So use simply (pt_.+_kor) to match everything between pt_ and _kor: preg_match('/(pt_+_kor)/',$str, $matches);
Here's a demo: https://regex101.com/r/qL4fW9/1
The ^ and $ that you have used in the regular expression means that the string should start with pt AND end with kor. But it's neither starting as such, nor ending with kor (in fact, ending with kor_7700).
Try removing the ^ and $, and you'll get the match:
preg_match('/pt_.*_kor/',$str, $matches);

I can't get preg_match to test if the entire string matches the regex

I'm using this regular expression to test if a username is valid:
[A-Za-z0-9 _]{3,12} when I test it for matches in a text editor with the string test'ing, it highlights 'test' and 'ing', but when I use the following code in PHP:
if(!preg_match('/[A-Za-z0-9 _]{3,12}/', $content) where $content is test'ing and it should return FALSE, it still returns true.
Is there something wrong with my regular expression? I need:
Minimum length 3, max 12 {3,12}
No spaces/underscores in front or after the string, and no spaces/underscores in a row anywhere
(I'm using additional checks for this because I'm not very good with regex)
Only alphanumerics, spaces and underscores allowed [A-Za-z0-9 _]
Thanks in advance...
You're missing the anchors in the regular expression, so the regex can comfortably match 3 characters in the character class anywhere in the string. This is not what you want. You want to check if your regex matches against the entire string. For that, you need to include the anchors (^ and $).
if(!preg_match('/^[A-Za-z0-9 _]{3,12}$/', $content)
^ ^
^ asserts the position at the beginning of the string and $ asserts position at the end of the string. It's important to note that these meta characters do not actually consume characters. They're zero-width assertions.
Further reading:
Regex Anchors on regular-expressions.info
The Stack Overflow Regular Expressions FAQ
You should add start and end anchors (^$):
if(!preg_match('/^[A-Za-z0-9 _]{3,12}$/', $content)
The anchor ^ matches the start of the string and $ matches the end. That way, it will only match if the whole string satisfies your regex.
Hope that helps

Trim a full string instead of using trim() with characters

When using a specific delimiter in a data string, often I want to trim off the last instance of it before exploding.
I have always wondered this:
PHP trim() will trim off whitespace, or certain characters. But what if I wanted to trim full strings, like so:
$data = 'cookieDELIMITERchocolateDELIMITER';
$data = trim($data, 'DELIMITER');
The above won't really work, since it won't trim the string "DELIMITER", but instead trim the characters "D,E,L,I,M,T,R".
What I want is this:
$data = 'cookieDELIMITERchocolate';
I appreciate your suggestions!
$data = 'cookieDELIMITERchocolateDELIMITER';
$data = preg_replace('/^(DELIMITER)*|(DELIMITER)*$/', '', $data);
var_dump($data);
// string(24) "cookieDELIMITERchocolate"
The regular expression ^(DELIMITER)*|(DELIMITER)*$ will match 0+ (*) instances of "DELIMITER" at the beginning (^) of a string or (|) the end ($) of the string. preg_replace() will take these matches and replace them with blank strings.
Full RegEx Explanation
^ # Matches the start of the string
(DELIMITER)* # Matches "DELIMITER" 0+ times, thanks to the *
| # OR
(DELIMITER)* # Matches "DELIMITER" 0+ times, thanks to the *
$ # Matches the end of the string
This means it will either match many DELIMITERs at the beginning OR the end of the string. Since preg_replace() does a global match/replace, it will get all occurrences of DELIMITER as long as they are either attached to the beginning or end of the string.
Adding the dot (^(DELIMITER).*|(DELIMITER)*$) would match the beginning of the string, followed by DELIMITER, followed by 0+ of any character (. matches all). This would effectively replace the entire string if it started with DELIMITER.
If you are using this to keep from having an empty array element after explode(), try this:
$array = array_filter(explode('DELIMITER', $data))

PHP search and replace regex pattern

I'm trying to get a string which matches by a regex pattern ( {$ ... } ). But I don't want the brackets and the $ sign returned.
For example
{$Testpath}/Testlink
should return
Testpath
My regex pattern looks like this at the moment:
^{\$.*}$
Try the following regex:
^\{\$\K[^}]*(?=\})
Regex101 Demo
This expression mathces start-of-string ^ then a literal { then a literal $ then it ignores those using \K anchor, then it matches one or more characters which aren't a } then it looks ahead (?=\}) for a literal }.
You may not need the end-of-line anchor $ because the text you are trying to match might not end at the end of the string and you may not need the start-of-line ^ anchor for the opposite reason, that is the pattern you are trying to match may not be at the start of the string or line.
I think you should remove ^ and $ and use the global modifier.

matching the regular expression with the whole string

im kinda strumped in a situation where i need to match a whole string with a regular expression rather than finding if the pattern exists in the string.
suppose if i have a regular expression
/\\^^\\w+\\$^/
what i want is that the code will run through various strings , compare the strings with the regular expression and perform some task if the strings start and end with a ^.
Examples
^hello world^ is a match
my ^hello world^ should not be a match
the php function preg_match matches both of the results
any clues ???
Anchor the ends.
/^...$/
Here is a way to do the job:
$strs = array('^hello world^', 'my ^hello world^');
foreach($strs as $str) {
echo $str, preg_match('/^\^.*\^$/', $str) ? "\tmatch\n" : "\tdoesn't match\n";
}
Output:
^hello world^ match
my ^hello world^ doesn't match
Actually, ^\^\w+\^$ will not match "^hello world^" because you have two words there; the regex is only looking for a single word enclosed by "^"s.
What you are looking for is: ^\^.*\^$
This will match "^^", "^hello world^", "^a very long string of characters^", etc. while not matching "hello ^world^".
You can use the regex:
^\^[\w\s]+\^$
^ is a regex meta-character which is used as start anchor. To match a literal ^ you need to escape it as \^.
So we have:
^ : Start anchor
\^: A literal ^
[\w\s]+ : space separated words.
\^: A literal ^
$ : End anchor.
Ideone Link
Another pattern is: ^\^[^\^]*\^$ if you want match "^hello world^" and not "hello ^world^" , while \^[^\^]*\^ if you want match "^hello world^" and world in the "hello ^world^" string.
For Will: ^\^.*\^$ this match also "^hello^wo^rld^" i think isn't correct.
Try
/^\^\s*(\w+\s*)+\^$/

Categories