Preg match is empty when regex test seems working - php

I am trying to make it with regex but obviously can't make it.
$matches = [];
preg_match("\[phpstart\](.*)\[phpend\]",$PiText,$matches);
In the https://regex101.com/ I tried and it returns result Group 1. With the correct value - echo "test" for this string [phpstart] echo "test" [phpend]. But in when I use it in the script, $matches is an empty array.

You need to add delimiter on your regex definition like / :
So your corrected preg_match is :
preg_match("/\[phpstart\](.*)\[phpend\]/",$PiText,$matches);
You need to have delimiter at the start and at the end of your regex definition

Related

Regular expression return only certain values PHP

I cant remember what to use to return only a specific part of a string.
I have a string like this:-
$str = "return(me or not?)";
I want to get the word which is after (. In this example me will be my result. How can I do this?
I dont think substr is what I am looking for. as substr returns value based on the index you provided. which in this case i dont know the index, it can vary. All I know is that I want to return whatever is after "(" and before the space " ". The index positions will always be different there for i cant use substr(..).
This regular expression should do the trick. Since you didn't provide general rules but only an example it might need further changes though.
preg_match('/\((\S+)/', $input, $matches);
$matches[1] contains "me" then.
<?php
// Your input string
$string = "return(me or not?)";
// Pattern explanation:
// \( -- Match opening parentheses
// ([^\s]+) -- Capture at least one character that is not whitespace.
if (preg_match('/\(([^\s]+)/', $string, $matches) === 1)
// preg_match() returns 1 on success.
echo "Substring: {$matches[1]}";
else
// No match found, or bad regular expression.
echo 'No match found';
Result of capture group will be your result using this regex and preg_match().
$regex = '/\((\w+)/';
Check preg_match() for the working reference.

Regular expression which matches a URL and return desired value

I need regular expression which matches a URL and return the desired value
Example (if the URL matches to)
1. http://example.com/amp
2. http://example.com/amp/
3. http://example.com/amp~
THEN
it should return: ?amp=1
ELSE
it should return: false
You should be able to use preg_replace to append ?amp= to the end of a matching string. Its functionality already does the if/else functional you require,
If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.
(or I misread the it should return noting)
-http://php.net/manual/en/function.preg-replace.php
Something like
amp\K( |\/|~)$
Should do it
$string = 'http://example.com/amp~';
echo preg_replace('/amp\K( |\/|~)$/', '$1?amp=1', $string);
The $1 is optional, not sure if you wanted the found character included or not.
PHP Demo: https://eval.in/780432
Regex demo: https://regex101.com/r/JgcrLu/1/
$ is the end of the string. () is a capturing and alteration group. |s are alterations. \K skips the previously matched regex part.
You didn't specify the programming language you're using but you probably need something like:
php:
$new = preg_replace('%/amp\b(?:/|~)?%si', '/?amp=1', $old);
python:
new_string = re.sub(r"/amp\b(?:/|~)?", "/?amp=1", old_string, 0, re.IGNORECASE)
Regex Demo

How to preg_match '{95}1340{113}1488{116}1545{99}1364'

i want to preg_match following as it is
$this_string = '{95}1340{113}1488{116}1545{99}1364';
My best try was
preg_match('/^[\{\d+\}\d+]+$/', $this_string);
That matches
{95}1340{113}1488
but also
{95}1340{113}
which is wrong.
I know why it is matching last example. One match {95}1340 was true, so '+' 'll be always true. But i don't know how to tell, if it match, so it has always be a complete match in '[…]'
i do expect only matches likes these
{…}…
{…}…{…}…
{…}…{…}…{…}…
one of the tries:
^(\{\d+\}\d+)+$
does also match
{99}1364
at the very last end of this string as a second match, so i get back an Array with two Elements:
Array[0] = {95}1340{113}1488{116}1545{99}1364 and
Array[1] = {99}1364
Problem is unnecessary use of character class in your regex i.e. [ and ].
You can use:
'/^(\{\d+\}\d+)+$/'
The translation of your regex to a clearer thing would be: /^[\{\}0-9+]+$/, this would be explained as everything that is inside this chracters {}0123456789+, exactly those ones.
What you want is grouping, for grouping, parentheses are needed and not character classes () instead [], so what you want to do is replace [] for ().
Short answer: '/^(\{\d+\}\d+)+$/'
What you are trying to do is a little unclear. Since your last edit, I assume that you want to check the global format of the string and to extract all items (i.e. {121}1231) one by one. To do that you can use this code:
$str = '{95}1340{113}1488{116}1545{99}1364';
$pattern = '~\G(?:{\d+}\d+|\z)~';
if (preg_match_all($pattern, $str, $matches) && empty(array_pop($matches[0])))
print_r($matches[0]);
\G is an anchor for the start of the string or the end of the previous match
\z is an anchor for the end of the string
The alternation with \z is only needed to check that the last match is at the end of the string. If the last match is empty, you are sure that the format is correct until the end.

PHP preg_match using 'or' delimiter

I'm trying to match a certain string of the url using preg_match but I need to match either one or the other string and I can't find the correct syntax.
What I'm using now is:
$is_url_en = preg_match ("/\b95\b/i", $iframeurl);
This searches for the number "95" in the url. However I also want to match "en" as well but I don't know how to use the 'or' delimiter. I've seen somewhere the following:
$is_url_en = preg_match ("/\b95\b/i|/\ben\b/i", $iframeurl);
...but it doesn't work. Any hints please?
Don't repeat the / and /i. Those delimit the regex so they should only be there once.
$is_url_en = preg_match ("/\b95\b|\ben\b/i", $iframeurl);
You could then simplify this to:
$is_url_en = preg_match ("/\b(95|en)\b/i", $iframeurl);

PHP echo -> string as 0?

how would I avoid that the following :
$_SESSION['myVar']=preg_match("[^a-zA-Z]",'',$_SESSION['myVar']);
echo $_SESSION['myVar'];
displays
0
and instead it displays/outputs the var content ? preg_match gives out mixed type, but this shouldnt be the problem...
Why, is the value of the string itself not addressable with echo (by comapring its contents, it is OK)?
Formerly I had
$_SESSION['myVar']=ereg_replace("[^a-zA-Z]",'',$_SESSION['myVar']);
ant the output óf ereg_replace was correctly displayed the variable content.
PCRE in PHP need delimiters [docs] and you probably want preg_replace [docs]:
preg_replace("/[^a-zA-Z]/",'',$_SESSION['myVar']);
Assuming you had preg_replace, even then, the brackets ([...]) would be interpreted as delimiters and so the engine would literally try to match a-zA-Z at the beginning of the string and would not interpret the constructor as character class.
preg_match returns an int, not mixed: http://php.net/manual/en/function.preg-match.php
Use the matches parameter to get your matches.
The problem is that preg_match returns a Boolean, 1 if the pattern was matched, 0 if it didn't. preg_match simply matches occurrences, it doesn't replace them. Here's how you use preg_match:
$matched = array();
preg_match("/[^a-zA-Z]/", $_SESSION["myVar"], $matches);
print_r($matches); // All matches are in the array.

Categories