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.
Related
I have a string that contains something like "LAB_FF, LAB_FF12" and I'm trying to use preg_replace to look for both patterns and replace them with different strings using a pattern match of;
/LAB_[0-9A-F]{2}|LAB_[0-9A-F]{4}/
So input would be
LAB_FF, LAB_FF12
and the output would need to be
DAB_FF, HAD_FF12
Problem is, for the second string, it interprets it as "LAB_FF" instead of "LAB_FF12" and so the output is
DAB_FF, DAB_FF
I've tried splitting the input line out using 2 different preg_match statements, the first looking for the {2} pattern and the second looking for the {4} pattern. This sort of works in that I can get the correct output into 2 separate strings but then can't combine the two strings to give the single amended output.
\b is word boundary. Meaning it will look at where the word ends and not only pattern match.
https://regex101.com/r/upY0gn/1
$pattern = "/\bLAB_[0-9A-F]{2}\b|\bLAB_[0-9A-F]{4}\b/";
Seeing the comment on the other answer about how to replace the string.
This is one way.
The pattern will create empty entries in the output array for each pattern that fails.
In this case one (the first).
Then it's just a matter of substr.
$re = '/(\bLAB_[0-9A-F]{2}\b)|(\bLAB_[0-9A-F]{4}\b)/';
$str = 'LAB_FF12';
preg_match($re, $str, $matches);
var_dump($matches);
$substitutes = ["", "DAB", "HAD"];
For($i=1; $i<count($matches); $i++){
If($matches[$i] != ""){
$result = $substitutes[$i] . substr($matches[$i],3);
Break;
}
}
Echo $result;
https://3v4l.org/gRvHv
You can specify exact amounts in one set of curly braces, e.g. `{2,4}.
Just tested this and seems to work:
/LAB_[0-9A-F]{2,4}/
LAB_FF, LAB_FFF, LAB_FFFF
EDIT: My mistake, that actually matches between 2 and 4. If you change the order of your selections it matches the first it comes to, e.g.
/LAB_([0-9A-F]{4}|[0-9A-F]{2})/
LAB_FF, LAB_FFFF
EDIT2: The following will match LAB_even_amount_of_characters:
/LAB_([0-9A-F]{2})+/
LAB_FF, LAB_FFFF, LAB_FFFFFF...
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
So I have a pretty large dump file that I have to extract specific content from it.
The file has record each containing specific numbers enclosed by ". Bellow is a sample part of the file:
Ali Rabi (CustomerId=["3453456"]) // need to get: 3453456
Mohammad Reza Saberi (CustomerId=["12328"]) // need to get: 12328
Currently I read line by line and get the IDs as bellow. the code works fine and I get the result I want:
$cid = substr($row, strpos($row, '[') +2, strpos($row, ']')-strpos($row, '[')-2);
echo $cid;
But doesn't PHP have a function for this? getting the string enclosed by some delimiters?
If all your records look like the ones you've mentioned, I think it's the perfect place where you could use regular expressions.
Regular Expressions help you to create and find patterns in a given String.
For your case, you could probably use :
if (preg_match("/[0-9]+/", "Ali Rabi (CustomerId=[\"3453456\"])", $matches)) {
echo "Match was found <br />";
echo $matches[0];
}
The preg_match() function helps you to find the matches. The first param for this function is the pattern you're looking for. In your case you're looking for a set of continuous digits each of which can range from 0-9.
So, for a single digit we use [0-9]. Adding a + after [0-9] means that there needs to be atleast one digit in the match. Hence, [0-9]+ as the regular expression.
Read more about regular expressions in php : http://webcheatsheet.com/php/regular_expressions.php
Try:
<?php preg_match_all("/([1-9]+)/",$yourtext, $result, PREG_PATTERN_ORDER); ?>
$result contains all Matches.
Further Infomartion: http://php.net/manual/de/function.preg-match-all.php
I think you can use str_replace to remove the "
$cid = str_replace('"','',$row);
I am having difficulties to understand preg_match function.An e.g is way better
$subject="XY=abC%3Fedr%3Damp;35"
I am trying to extract
bC%3Fed
using preg_match and store it in variable
if(preg_match($pattern, $subject, $matches))
{
$string = $matches[1];
}
echo $string;
Here are the different variation that i use for $pattern
I want to use # as a delimeter
#bC(.*?)#
#bC.*?#
I just don't understand why its not working , i guess something is wrong in the $pattern.
Please don't use complicated regex and try to fix my attempt as the aim here is to understand how preg_match works and what is wrong here.
Regards
Using # as the delimiter is OK, but the regex is wrong. I guess you want:
#(bC.*?)r# // matches #bC and the following characters unless and 'r' (see comments)
A good starting point to learn the regex syntax is the PCRE manual
Example:
$subject="XY=abC%3Fedr%3Damp;35";
$pattern="#(bC.*?)r#";
preg_match($pattern, $subject, $matches);
$string = $matches[1];
echo $string; // bC%3Fed
The ? after .* switches the greediness of the pattern. By default patterns are greedy, they try to find the longest match. So you .*? means any char, any count, smallest match. Because here is nothing after that will anchor it, the smallest possible match is an empty string.
I want to find the first matching string in a very very long text. I know I can use preg_grep() and take the first element of the returned array. But it is not efficient to do it like that if I only need the first match (or I know there is exactly only one match in advance). Any suggestion?
preg_match() ?
preg_match() returns the number of
times pattern matches. That will be
either 0 times (no match) or 1 time
because preg_match() will stop
searching after the first match.
preg_match_all() on the contrary will
continue until it reaches the end of
subject. preg_match() returns FALSE if
an error occurred.
Here's an example of how you can do it:
$string = 'A01B1/00asdqwe';
$pattern = '~^[A-Z][0-9][0-9][A-Z][0-9]+~';
if (preg_match($pattern, $string, $match) ) {
echo "We have matched: $match[0]\n";
} else {
echo "Not matched\n";
}
You can try print_r($match) to check the array structure and test your regex.
Side note on regex:
The tilde ~ in the regex are just delimiters needed to wrap around
the pattern.
The caret ^ denote that we are matching from the start
of the string (optional)
The plus + denotes that we can have one or
more integers that follow. (So that A01B1, A01B12, A01B123 will also
be matched.