This question already has answers here:
Parsing URL query in PHP [duplicate]
(5 answers)
Closed 1 year ago.
I use php function sscanf to parse string and extrac parameters.
This code :
$s='myparam1=hello&myparam2=world';
sscanf($s, 'myparam1=%s&myparam2=%s', $s1, $s2);
var_dump($s1, $s2);
displays :
string(20) "hello&myparam2=world" NULL
but i would like string hello in $s1 and strin world in $s2.
Any help?
%s isn't an equivalent to \w in regexp: it doesn't pick up only alphanumerics
$s='myparam1=hello&myparam2=world';
sscanf($s, 'myparam1=%[^&]&myparam2=%s', $s1, $s2);
var_dump($s1, $s2);
but using parse_str() might be a better option for you in this case
$s='myparam1=hello&myparam2=world';
parse_str($s, $sargs);
var_dump($sargs['myparam1'], $sargs['myparam2']);
How about using regular expressions?
Here is an example:
$string = 'myparam1=hello&myparam2=world';
// Will use exactly the same format
preg_match('/myparam1=(.*)&myparam2=(.*)/', $string, $matches);
var_dump($matches); // Here ignore first result
echo("<br /><br />");
// Will match two values no matter of the param name
preg_match('/.*=(.*)&.*=(.*)/', $string, $matches);
var_dump($matches); // Here ignore first result too
echo("<br /><br />");
// Will match all values no matter of the param name
preg_match('/=([^&]*)/', $string, $matches);
var_dump($matches);
I all three cases the matches array will contain the params.
I'm pretty convinced that it's better.
Good luck!
Related
This question already has answers here:
What is the difference between .*? and .* regular expressions?
(3 answers)
Closed 4 years ago.
I have a string:
$str = '{:de}Hallo Welt{:}{:en}Helo world{:}';
now i need to get substring for setted language.
$placeholder = '{:en}';
$lang_content = preg_replace('/(.*)'.preg_quote($placeholder).'(.*)'.preg_quote('{:}').'(.*)/sm', '\2', $str);
in case of value for placeholder {:en} i get Helo world as value for $lang_content, it works fine, but in case {:de} i get Hallo Welt{:}{:en}Helo world.
How can it be fixed? thanx!
You need to make the regex lazy by adding a ? in the second capture.
$str = '{:de}Hallo Welt{:}{:en}Helo world{:}';
$placeholder = '{:de}';
$lang_content = preg_replace('/(.*)'.preg_quote($placeholder).'(.*?)'.preg_quote('{:}').'(.*)/sm', '\2', $str);
echo $lang_content; // Hallo Welt
https://3v4l.org/m6AGF
An optional method would be to use preg_match to get an associative array.
$str = '{:de}Hallo Welt{:}{:en}Helo world{:}';
preg_match_all("/\{:(.*?)}(.*?)\{/", $str, $matches);
$matches = array_combine($matches[1], $matches[2]);
var_dump($matches);
echo $matches["de"]; // Hallo Welt
https://3v4l.org/ELB2B
With the Ungreedy flag (U).
You can update the flags at the end of your regex from /sm to /smU for the result to stop at the next occurrence of {:} in the string and not at the last one.
If the string is to contain several occurrences, maybe you can also add the global (g) flag so the regex doesn't stop after the first one.
You can test it here: https://regex101.com/r/4XSPoz/3
By the way, it seems that your are using preg_replace as a way to find a substring and don't actually need to replace it in the result, maybe you should use preg_match instead.
This question already has answers here:
Retrieve all hashtags from a tweet in a PHP function
(5 answers)
Closed 6 years ago.
I have this sentence
"My name's #jeff,what is thy name?"
And now i want to get #jeff from this sentence.
I have tried this code
for ($i=0; $i <=substr_count($Text,'#'); $i++) {
$a=explode('#', $Text);
echo $a[$i];
}
But it returns #jeff,what is thy name? which is not what my soul desires
There is simpler solution to do it. Use preg_match() that find target part of string using regex.
preg_match("/#\w+/", $str, $matches);
echo $matches[0]
Check result of code in demo
If you want to get all matches string, use preg_match_all() that find all matches.
preg_match_all("/#\w+/", $str, $matches);
print_r($matches[0]);
Personally I would not capture the word with #, since a hashtag is only an identifier for your code to get the attached word.
$re = '/(?<!\S)#([A-Za-z_][\w_]*)/';
$str = "My name's #jeff,what #0is #thy name?";
preg_match_all($re, $str, $matches);
// Print the entire match result
print_r($matches[0]); // #jeff, #thy
print_r($matches[1]); // jeff, thy
By the rules of hashtags, it may not start with a digit but may contain them.
I am using the startsWith() function here startsWith() and endsWith() functions in PHP
But I want it to only match full words.
Currently it will match the following:
hi
high
hiho
But I want it to only match "hi", not the other two words if the input is:
hi there
You can match it with this regular expression: /^hi$|^hi\s|\shi\s|\shi$/
$test = ['hi', 'hi there', 'high', 'hiho'];
$pattern = '/^hi$|^hi\s|\shi\s|\shi$/';
$matches = [];
foreach ($test as $t) {
var_dump($t);
preg_match($pattern, $t, $matches);
var_dump($matches);
}
Parts explained:
^hi$ - your sting is "hi"
^hi\s - your string starts with hi: "hi "
\shi\s - there's a " hi " somewhere in your string
\shi$ - your string ends with " hi"
Those parts are glued together with pipe "|", which in regex means "or", so the entire expression is matching any one of the parts
If you test whole text against hi words, try this:
<?php
preg_match_all('#hi\s#i',
"hi me
hi there
high
highlander
historic
hire",
$matches);
var_dump($matches);
Test it - modify here: https://regex101.com/r/tV3jR6/1
This question already has answers here:
PHP substring extraction. Get the string before the first '/' or the whole string
(14 answers)
Closed 12 months ago.
I need to find a way in PHP to remove the last portions of 2 strings using regex's. This way once they are stripped of the extra characters I can find a match between them. Here is an example of the type of string data I am dealing with:
categories_widget-__i__
categories_widget-10
So I would like to remove:
-__i__ from the first string
-10 from the second string
Thanks in advance.
(.*)-
This simple regex can do your job if - is the splitting criteria
See demo.
http://regex101.com/r/rX0dM7/7
$str1 = "categories_widget-__i__";
$str2 = "categories_widget-10";
$arr1 = explode("-", $str1);
$arr2 = explode("-", $str2);
echo $arr1[0];
echo $arr2[0];
Is the last occurrence of a hyphen the only thing that's important? If so you don't need regex:
$firstPart = substr($str, 0, strrpos($str, '-'));
ยป example
You could try the below code to remove all the characters from - upto the last.
<?php
$text = <<<EOD
categories_widget-__i__
categories_widget-10
EOD;
echo preg_replace("~-.*$~m","",$text);
?>
Output:
categories_widget
categories_widget
- matches the literal - symbol. And .* matches any character following the - symbol upto the end of the line. $ denotes the end of a line. By replacing all the matched characters with an empty string would give you the desired output.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
a simple function for return number from string in php
What's the best/most efficient method to extract a specific set of numbers from a string? For example: I want to get the set of numbers immediately after Case# in sring "blah blah Case#004522 blah blah". I imagine the number of numeric characters after Case# will always be the same but I would like the code to not make that assumption as I have been.
So far I have been using a strpos method to locate Case# and then pull a specific number of characters afterwords using substr. I just feel like this is clunky. Maybe preg_match would be more effective or simplified?
$text = "blah blah Case#004552 blah blah";
$find = strpos($text,'Case#');
if ( $find )
$numbers = substr($text, $find+5, 6);
You can make use of regular expressions to first match your pattern of characters (Case#) and then you expect to match numbers only (digits), that is \d in PCRE (Demo):
$numbers = preg_match("/Case#(\d+)/", $text, $matches)
? (int)$matches[1]
: NULL
;
unset($matches);
For multiple (integer) matches at once:
$numbers = preg_match_all("/Case#(\d+)/", $text, $matches)
? array_map('intval', $matches[1])
: NULL
;
unset($matches);
You can locate it as you do it already, and then scan for the number (Demo):
$find = strpos($text, 'Case#');
sscanf(substr($text, $find), 'Case#%d', $numbers);
Use PHP's preg_match and following regex:
(?<=case#)[0-9]+
You can test # http://regexr.com?31jdv
The simplest solution is
if (preg_match('/Case#\s*(\d+)/i', $test, $m)) {
$numbers = $m[1];
}