I have a string like "1X6TAB". Now I apply some regular expression to this string to remove "TAB" and replacing "X" with "*", so my final string will be "1*6". The expected result is "6", but I get "1*6" as the result.
Code:
Regexonlynumber("1X6TAB");
function Regexonlynumber($number){
$number = preg_replace("/[^0-9.X]/", '', $number);
echo str_replace('X',"*",$number);die;
}
Instead of str_replace(), you can explode() it by 'X' delimiter, then use array_product().
Regexonlynumber("1X6TAB");
function Regexonlynumber($number){
$number = preg_replace("/[^0-9.X]/", '', $number);
echo array_product(explode('X', $number));
}
You are almost there. Just add one step more to explode and multiply, like this:
<?php
function Regexonlynumber($number){
$number = preg_replace("/[^0-9.X]/", '', $number);
$arr = explode("X", $number);
echo $arr[0]*$arr[1];
}
Regexonlynumber("2X6TAB");
?>
Demo.
You can even just do it like:
function Regexonlynumber($number){
$arr = explode("X", $number);
echo $arr[0]*$arr[1];
}
Demo.
It's better to use eval(), which will also be able to compute more complex expressions:
Regexonlynumber("3X6-13TAB");
function Regexonlynumber($number){
$number = preg_replace("/[^0-9.X\-\+\/]/", '', $number);
$str = str_replace('X',"*",$number);
eval("\$result = {$str};");
echo $str . " = " . $result . "\n";
}
Regexonlynumber() function help you to to get product of numbers from string
array_product() Function :- The array_product() function calculates and returns the product of an array.
str_split() Function :- The str_split() function splits a string into an array.
<?php
function Regexonlynumber($number){
$number = preg_replace("/[^0-9,.]/", "", $number);
echo array_product(str_split($number));
}
Regexonlynumber("1X6TAB");
?>
Related
How can i remove " " from array start and after array end. I need array only without the "
public function showPatientModal(Request $request)
{
$patient_id = $request->input('id');
$data['patient'] = Patient::with('cases')->where('id', $patient_id)->first();
$files_before = $data['patient']->file_before;
$files_after = $data['patient']->file_after;
dd($files_before);
}
return me the following but i am getting the array as a string
"["download (2).jpg","download (3).jpg","download.jpg"]"
$string = '"["download (2).jpg","download (3).jpg","download.jpg"]"';
echo substr($string, 1, -1);
<?php
$string = '"["download (2).jpg","download (3).jpg","download.jpg"]"';
$string = preg_replace('/(?<=^)\s*"\s*(?=\[)/', '', preg_replace('/(?<=\])\s*"\s*(?=$)/', '', $string));
echo $string;
I haven't tested this, but it should work.
Btw, if you want to pass that to javascript, you're better off using json_encode instead.
I need to find out if there are any redundant words in string or not .Is there any function that can provide me result in true/false.
Example:
$str = "Hey! How are you";
$result = redundant($str);
echo $result ; //result should be 0 or false
But for :
$str = "Hey! How are are you";
$result = redundant($str);
echo $result ; //result should be 1 or true
Thank you
You could use explode to generate an array containing all words in your string:
$array = explode(" ", $str);
Than you could prove if the arrays contains duplicates with the function provided in this answer:
https://stackoverflow.com/a/3145660/5420511
I think this is what you are trying to do, this splits on punctuation marks or whitespaces. The commented out lines can be used if you want the duplicated words:
$str = "Hey! How are are you?";
$output = redundant($str);
echo $output;
function redundant($string){
$words = preg_split('/[[:punct:]\s]+/', $string);
if(max(array_count_values($words)) > 1) {
return 1;
} else {
return 0;
}
//foreach(array_count_values($words) as $word => $count) {
// if($count > 1) {
// echo '"' . $word . '" is in the string more than once';
// }
//}
}
References:
http://php.net/manual/en/function.array-count-values.php
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.preg-split.php
Regex Demo: https://regex101.com/r/iH0eA6/1
i have one string
$str ='california 94063';
now i want california and 94063 both in diferent variable.
string can be anything
Thanks in advance....
How about
$strings = explode(' ', $str);
Assuming that your string has ' ' as a separator.
Then, if you want to find the numeric entries of the $strings array, you can use is_numeric function.
Do like this
list($str1,$str2)=explode(' ',$str);
echo $str2;
If your string layout is always the same (say: follows a given format) then I'd use sscanf (http://www.php.net/manual/en/function.sscanf.php).
list($str, $number) = sscanf('california 94063, "%str %d");
<?php
$str ='california 94063';
$x = preg_match('(([a-zA-Z]*) ([0-9]*))',$str, $r);
echo 'String Part='. $r[1];
echo "<br />";
echo 'Number Part='.$r[2];
?>
If text pattern can be changed then I found this solution
Source ::
How to separate letters and digits from a string in php
<?php
$string="94063 california";
$chars = '';
$nums = '';
for ($index=0;$index<strlen($string);$index++) {
if(isNumber($string[$index]))
$nums .= $string[$index];
else
$chars .= $string[$index];
}
echo "Chars: -".trim($chars)."-<br>Nums: -".trim($nums)."-";
function isNumber($c) {
return preg_match('/[0-9]/', $c);
}
?>
php noob here trying to create a function but can't quite find the resource on the web that rids my confusions. Here it goes;
I want to create a function which takes a variable name, for example
Thief's Wit (4)
And converts it to
thiefswit.jpg
So far, here is what I have
THIS CODE IS LOADED TO TEST MY FUNCTION
require_once 'functions.php';
$mod = "Thief's Wit (4)";
convertImage($mod);
echo $mod;
?>
THIS CODE IS THE ACTUAL FUNCTION
function convertImage($string)
{
$string = preg_replace('/\s+/', '', $string);
$string = str_replace("'", "", $string);
$stringlength = strlen($string);
substr ($string, 0, ($stringlength-4));
$string = strtolower ($string);
$string = "$string" . ".jpg";
return $string;
}
?>
The format of the strings will always be
NAME HERE (4)
which is why I substr the length-4.
When I run this function, it echoes the original string.
Any help here?
I'm new to PHP and don't really understand
a) What the 'return' does at the end of the function and
b) Does the function inherently know to replace "$string" with the variable you tell it to act on in another file? In this case $mod.
Thanks!
You need to save the output of the function:
$mod = "Thief's Wit (4)";
$mod = convertImage($mod); // save the return value to $mod variable
echo $mod;
The return value of a function is the value you get from calling a function. So convertImage($mod) will have the value that you return. At this point, you need to store the results to a variable, which you can do by doing $mod = convertImage($mod);
An alternative would be to "pass by reference", where modifying the arguments of your function will modify the variables themselves.
function convertImage(&$string) // use &$string to pass by reference
{
$string = preg_replace('/\s+/', '', $string);
$string = str_replace("'", "", $string);
$stringlength = strlen($string);
substr ($string, 0, ($stringlength-4));
$string = strtolower ($string);
$string = "$string" . ".jpg";
//return $string; this won't be needed anymore
}
...
$mod = "Thief's Wit (4)";
convertImage($mod);
echo $mod;
You have to either return the new string you created
$mod = convertImage($mod);
Or pass by reference, which means that the function convertImage is working with the same reference to the passed in string as its caller
function convertImage(&$string) {...}
convertImage($mod); // $mod will point to a new string after the call
function convertImage(&$string) {
$string = strtolower(preg_replace("/[^a-zA-Z]+/", "", $string));
}
should do all you need - it will strip any punctuation and numbers etc, and make it lower case.
edited to allow passing by reference
You aren't assigning the variable value anywhere. To get the actual result, you'd have the function return value to a variable, like so:
$mod = convertImage($mod);
Once the actual function output is stored in a variable, you'll be able to use it anywhere as you like.
Demo: http://codepad.org/naFB74K6
<?php
function convertImage(&$string)
{
$string = preg_replace('/\s+/', '', $string); //Thief'sWit(4)
$string = str_replace("'", "", $string); //ThiefsWit(4)
$string = substr($string, 0, strlen($string)-3); //ThiefsWit
$string = strtolower($string); //thiefswit
return $string.".jpg";
}
$mod = "Thief's Wit (4)";
convertImage($mod);
echo $mod;
?>
In PHP, how can you replace the second and third character of a string with an X so string would become sXXing?
The string's length would be fixed at six characters.
Thanks
It depends on what you are doing.
In most cases, you will use :
$string = "string";
$string[1] = "X";
$string[2] = "X";
This will sets $string to "sXXing", as well as
substr_replace('string', 'XX', 1, 2);
But if you want a prefect way to do such a cut, you should be aware of encodings.
If your $string is 我很喜欢重庆, your output will be "�XX很喜欢" instead of "我XX欢重庆".
A "perfect" way to avoid encoding problems is to use the PHP MultiByte String extension.
And a custom mb_substr_replace because it has not been already implemented :
function mb_substr_replace($output, $replace, $posOpen, $posClose) {
return mb_substr($output, 0, $posOpen) . $replace . mb_substr($output, $posClose + 1);
}
Then, code :
echo mb_substr_replace('我很喜欢重庆', 'XX', 1, 2);
will show you 我XX欢重庆.
Simple:
<?php
$str = "string";
$str[1] = $str[2] = "X";
echo $str;
?>
For replacing, use function
$str = 'bar';
$str[1] = 'A';
echo $str; // prints bAr
or you could use the library function substr_replace as:
$str = substr_replace($str,$char,$pos,1);
similarly for 3rd position
function mb_substr_replace($string, $replacement, $start, $length=0)
{
return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start+$length);
}
same as above, but standardized to be more like substr_replace (-substr- functions usually take length, not end position)