how to call funtion on preg match php code - php

i have code..
<?php
function word()
{
$arr = array("/c/","/b/","/c/");
echo $arr[array_rand($arr)];
}
$text = "a";
if(preg_match("$word()", $text)) {
$result = "found";
}else{
$result = "not found";
}
echo $result;
?>
how to call function word(); into preg_match.
I want to randomly search the words in preg_match.
I tried but it didn't work.
how to fix this code.
Thanks

If you make your function word() return the random string instead of echoing it you can use it as any value by calling the function.
function word() {
$arr = array("/c/","/b/","/c/");
return $arr[array_rand($arr)];
}
if( preg_match(word(), $text) ) {
$result = "found";
}
else {
$result = "not found";
}
echo $result;
If it makes it more clear, this is the same as storing the result from the function in a variable and use that.
These are all the same:
// Writing the pattern in place.
preg_match("/a/", $text);
// Storing it in a variable before use.
$to_match = "/a/";
preg_match($to_match, $text);
// Storing it in a variable where the value is returned from a function.
$to_match = word();
preg_match($to_match, $text);
// Using a function directly in the call to `preg_match`.
preg_match(word(), $text);

Related

remove front and last of the character of a string in php

My goal is to create a function that removes the first and last characters of a string in php.
My code:
function remove_char(string $s): string {
$len = strlen($s);
return substr($s,1,$len-2);
}
This not past the codewar code test. Can anyone tell me why it is not correct?
The built in function substr is accepting negative value, when you use negative value it affect readability. You can also give the function name better and clearer name like so:
function modify_string(string $s): string {
return substr($s, 1, -1);
}
try this code.
function remove_char(string $s){
if(strlen($s) > 1){
return substr($s, 1, -1);
}
return false;
}
<?php
function remove($word){
$result = substr($word, 1, -1);
return $result;
}
$word = 'HELLO';
$results = remove($word);
echo $results;
?>
Demo

check characters are available or not in array

I have two variables such as below
$string1 = array('A','b','c');
$string2 = 'bAcdadbcliek'
need to check all the characters from string1 is presents in string2 or not in php and values are dynamic.
try This
<?php
$string1 = array('A','b','c','2');
$string2 = 'bAcdadbcliek';
foreach($string1 as $newstring)
{
$finalval=strrchr($string2,$newstring);
if($finalval!="")
{
echo $newstring." ---: Available in given String<br/>";
}
else
{
echo $newstring." ---: Not Available in given String<br/>";
}
}
?>
use str_split and array_intersect
<?php
$string1 = array('A','b','c');
$string2 = 'bAcdadbcliek';
$new = str_split($string2);
$new_2 = array_intersect($string1,$new);
if(count($new_2)==count($string1))
{
echo "all matched";
}
else
{
echo "not ";
}
?>
The following function will return a boolean true/false if all values are matched. It is case-sensitive.
Basically, split $string2 into an array and intersect it, match the count of that against the count of $string1 (which is an array, not a string by the way). If the count is equal, everything was found.
$string1 = array('A','b','c');
$string2 = 'bAcdadbcliek';
function match_string(string $string, array $match_values) {
if (count(array_intersect(str_split($string), $match_values)) == count($match_values))
return true;
return false;
}
Live demo

Php - Foreach returning one value, first or last

If I use return in my function, I will get only one value.
If I use echo, I get all the values. I don't get it.
foreach($matches[0] as $matchbun)
{
$var1 = str_split($matchbun, 34);
$replace_line = "-";
$var_final = str_replace($replace_line, " ", $var1[1]);
$replace_url = array('google.com', '/name/');
$replace_url_with = array('yahoo.com', '/url_');
$url_final = str_replace($replace_url, $replace_url_with, $matchbun);
return ''.ucfirst($url_final).'';
}
Seems that I can't insert the echoes into a database, they appear blank if I run the function.
What to do?
When you have a return the code would not execute further. Generate the whole data, then return that data.
You can either built an array. Like -
$urls= array();
foreach($matches[0] as $matchbun)
{
.....
$urls[]= ucfirst($url_final);
}
return $urls;
Or You can generate a string. Like -
$urls= '';
foreach($matches[0] as $matchbun)
{
.....
$urls.= ucfirst($url_final);
}
return $urls;
Well, if you use return, you'll exit from that function on first iteration.
If you use echo, you are not exiting the function, you are echoing every iteration of the foreach loop.
Take return out of loop. and put data you want to return in a variable. Like this:
foreach($matches[0] as $matchbun)
{
$var1 = str_split($matchbun, 34);
$replace_line = "-";
$var_final = str_replace($replace_line, " ", $var1[1]);
$replace_url = array('google.com', '/name/');
$replace_url_with = array('yahoo.com', '/url_');
$url_final = str_replace($replace_url, $replace_url_with, $matchbun);
$myNewVariable .= $url_final;
}
return $myNewVariable;

substr() function for array PHP

I have a code that will produce array of strings.... now my problem is i need to substr each result of the array but i think array is not allowed to be used in substr...
please help:
CODE:
<?php
$file = 'upload/filter.txt';
$searchfor = $_POST['search'];
$btn = $_POST['button'];
$sum = 0;
if($btn == 'search') {
//prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
$result = implode("\n", $matches[0]);
echo $result;
}
else{
echo "No matches found";
}
}
?>
The $matches there is the array... i need to substr each result of the $matches
you can use array_walk:
function fcn(&$item) {
$item = substr(..do what you want here ...);
}
array_walk($matches, "fcn");
Proper use of array_walk
array_walk( $matches, substr(your area));
Array_map accepts several arrays
array_map(substr(your area), $matches1, $origarray2);
in your case
array_map(substr(your area), $matches);
Read more:
array_map
array_walk
To find a sub string in an array I use this function on a production site, works perfectly.
I convert the array to a collection because it's easier to manage.
public function substrInArray($substr, Array $array) {
$substr = strtolower($substr);
$array = collect($array); // convert array to collection
return $body_types->map(function ($array_item) {
return strtolower($array_item);
})->filter(function ($array_item) use ($substr) {
return substr_count($array_item, $substr);
})->keys()->first();
}
This will return the key from the first match, it's just an example you can tinker. Returns null if nothing found.

Convert string to array value in PHP

If I had an array such as:
testarray = array('foo'=>34, 'bar'=>array(1, 2, 3));
How would I go about converting a string such as testarray[bar][0] to find the value its describing?
Well, you can do something like this (Not the prettiest, but far safer than eval)...:
$string = "testarray[bar][0]";
$variableBlock = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
$regex = '/^('.$variableBlock.')((\[\w+\])*)$/';
if (preg_match($regex, $string, $match)) {
$variableName = $match[1]; // "testarray"
if (!isset($$variableName)) {
//Error, the variable does not exist
return null;
} else {
$array = $$variableName;
if (preg_match_all('/\[(\w+)\]/', $match[2], $matches)) {
foreach ($matches[1] as $match) {
if (!is_array($array)) {
$array = null;
break;
}
$array = isset($array[$match]) ? $array[$match] : null;
}
}
return $array;
}
} else {
//error, not in correct format
}
You could use PHP's eval function.
http://php.net/manual/en/function.eval.php
However, make absolutely sure the input is sanitized!
Cheers

Categories