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.
Related
I'm trying to lowercase every character in a string except for the last one that should be in uppercase.
Here is my code:
function caps_caps($var) {
$var = strrev(ucwords(strrev($var)));
echo $var;
}
caps_caps("HeLlo WOrld"); // should returns "hellO worlD"
This is the easy solution of this problem
function caps_caps($var) {
$var = strrev(ucwords(strrev(strtolower($var))));
echo $var;
}
caps_caps("HeLlo WOrld");
Demo
You also need to convert the string to lowercase first.
function caps_caps($var) {
$var = strrev(ucwords(strrev(strtolower($var))));
echo $var;
}
caps_caps("HeLlo WOrld"); // returns "hellO worlD"
function caps_caps($text) {
$value_to_print = '';
$text = strrev(ucwords(strrev($text)));
$words = explode(' ', $text);
foreach($words as $word){
$word = strtolower($word);
$word[strlen($word)-1] = strtoupper($word[strlen($word)-1]);
$value_to_print .= $word . ' ';
}
echo trim($value_to_print);
}
caps_caps("HeLlo WOrld");
You can try this piece of code.
function uclast($s)
{
$lastCharacterUppar = '';
if ( preg_match('/\s/',$s) ){//If string has space
$explode = explode(' ',$s);
for($i=0;$i<count($explode);$i++){
$l=strlen($explode[$i])-1;
$explode[$i] = strtolower($explode[$i]);
$explode[$i][$l] = strtoupper($explode[$i][$l]);
}
$lastCharacterUppar = implode(' ', $explode);
} else { //if string without space
$l=strlen($s)-1;
$s = strtolower($s);
$s[$l] = strtoupper($s[$l]);
$lastCharacterUppar = $s;
}
return $lastCharacterUppar;
}
$str = 'hey you yo';
echo uclast($str);
Try this, you forgot to do foreach, each elements.
function uclast_words($text, $delimiter = " "){
foreach(explode($delimiter, $text) as $value){
$temp[] = strrev(ucfirst(strrev(strtolower($value))));
}
return implode($delimiter, $temp);
}
print_r(uclast_words("hello world", " "));
I hope this is the answer of your question.
Here is a multibyte safe technique that performs the title-casing with one call instead of two. The string reversal and re-reversal is still necessary.
Code: (Demo)
echo strrev(
mb_convert_case(
strrev('HeLlo WOrld'),
MB_CASE_TITLE
)
);
// hellO worlD
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");
?>
I'm a newbie in PHP ,andnow I'm struck on this problem . I have a string like this :
$string = "qwe,asd,zxc,rty,fgh,vbn";
Now I want when user click to "qwe" it will remove "qwe," in $string
Ex:$string = "asd,zxc,rty,fgh,vbn";
Or remove "fhg,"
Ex:$string = "asd,zxc,rty,vbn";
I try to user str_replace but it just remove the string and still have a comma before the string like this:
$string = ",asd,zxc,rty,fgh,vbn";
Anyone can help? Thanks for reading
Try this out:
$break=explode(",",$string);
$new_array=array();
foreach($break as $newData)
{
if($newData!='qwe')
{
$new_array[]=$newData;
}
}
$newWord=implode(",",$new_array);
echo $newWord;
In order to achieve your objective, array is your best friend.
$string = "qwe,asd,zxc,rty,fgh,vbn";
$ExplodedString = explode( "," , $string ); //Explode them separated by comma
$itemToRemove = "asd";
foreach($ExplodedString as $key => $value){ //loop along the array
if( $itemToRemove == $value ){ //check if item to be removed exists in the array
unset($ExplodedString[$key]); //unset or remove is found
}
}
$NewLook = array_values($ExplodedString); //Re-index the array key
print_r($NewLook); //print the array content
$NewLookCombined = implode( "," , $NewLook);
print_r($NewLookCombined); //print the array content after combined back
here the solution
$string = "qwe,asd,zxc,rty,fgh,vbn";
$clickword = "vbn";
$exp = explode(",", $string);
$imp = implode(" ", $exp);
if(stripos($imp, $clickword) !== false) {
$var = str_replace($clickword," ", $imp);
}
$str = preg_replace('/\s\s+/',' ', $var);
$newexp = explode(" ", trim($str));
$newimp = implode(",", $newexp);
echo $newimp;
You could try preg_replace http://uk3.php.net/manual/en/function.preg-replace.php if you have the module set up. It will allow you to optionally replace trailing or leading commas easily:
preg_replace("/,*$providedString,*/i", '', "qwe,asd,zxc,rty,fgh,vbn");
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;
?>
when we add a param to the URL
$redirectURL = $printPageURL . "?mode=1";
it works if $printPageURL is "http://www.somesite.com/print.php", but if $printPageURL is changed in the global file to "http://www.somesite.com/print.php?newUser=1", then the URL becomes badly formed. If the project has 300 files and there are 30 files that append param this way, we need to change all 30 files.
the same if we append using "&mode=1" and $printPageURL changes from "http://www.somesite.com/print.php?new=1" to "http://www.somesite.com/print.php", then the URL is also badly formed.
is there a library in PHP that will automatically handle the "?" and "&", and even checks that existing param exists already and removed that one because it will be replaced by the later one and it is not good if the URL keeps on growing longer?
Update: of the several helpful answers, there seems to be no pre-existing function addParam($url, $newParam) so that we don't need to write it?
Use a combination of parse_url() to explode the URL, parse_str() to explode the query string and http_build_query() to rebuild the querystring. After that you can rebuild the whole url from its original fragments you get from parse_url() and the new query string you built with http_build_query(). As the querystring gets exploded into an associative array (key-value-pairs) modifying the query is as easy as modifying an array in PHP.
EDIT
$query = parse_url('http://www.somesite.com/print.php?mode=1&newUser=1', PHP_URL_QUERY);
// $query = "mode=1&newUser=1"
$params = array();
parse_str($query, $params);
/*
* $params = array(
* 'mode' => '1'
* 'newUser' => '1'
* )
*/
unset($params['newUser']);
$params['mode'] = 2;
$params['done'] = 1;
$query = http_build_query($params);
// $query = "mode=2&done=1"
Use this:
http://hu.php.net/manual/en/function.http-build-query.php
http://www.addedbytes.com/php/querystring-functions/
is a good place to start
EDIT: There's also http://www.php.net/manual/en/class.httpquerystring.php
for example:
$http = new HttpQueryString();
$http->set(array('page' => 1, 'sort' => 'asc'));
$url = "yourfile.php" . $http->toString();
None of these solutions work when the url is of the form:
xyz.co.uk?param1=2&replace_this_param=2
param1 gets dropped all the time
.. which means it never works EVER!
If you look at the code given above:
function addParam($url, $s) {
return adjustParam($url, $s);
}
function delParam($url, $s) {
return adjustParam($url, $s);
}
These functions are IDENTICAL - so how can one add and one delete?!
using WishCow and sgehrig's suggestion, here is a test:
(assuming no anchor for the URL)
<?php
echo "<pre>\n";
function adjustParam($url, $s) {
if (preg_match('/(.*?)\?/', $url, $matches)) $urlWithoutParams = $matches[1];
else $urlWithoutParams = $url;
parse_str(parse_url($url, PHP_URL_QUERY), $params);
if (strpos($s, '=') !== false) {
list($var, $value) = split('=', $s);
$params[$var] = urldecode($value);
return $urlWithoutParams . '?' . http_build_query($params);
} else {
unset($params[$s]);
$newQueryString = http_build_query($params);
if ($newQueryString) return $urlWithoutParams . '?' . $newQueryString;
else return $urlWithoutParams;
}
}
function addParam($url, $s) {
return adjustParam($url, $s);
}
function delParam($url, $s) {
return adjustParam($url, $s);
}
echo "trying add:\n";
echo addParam("http://www.somesite.com/print.php", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?newUser=1", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?newUser=1&fee=0", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?newUser=1&fee=0&", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?mode=1", "mode=3"), "\n";
echo "\n", "now trying delete:\n";
echo delParam("http://www.somesite.com/print.php?mode=1", "mode"), "\n";
echo delParam("http://www.somesite.com/print.php?mode=1&newUser=1", "mode"), "\n";
echo delParam("http://www.somesite.com/print.php?mode=1&newUser=1", "newUser"), "\n";
?>
and the output is:
trying add:
http://www.somesite.com/print.php?mode=3
http://www.somesite.com/print.php?mode=3
http://www.somesite.com/print.php?newUser=1&mode=3
http://www.somesite.com/print.php?newUser=1&fee=0&mode=3
http://www.somesite.com/print.php?newUser=1&fee=0&mode=3
http://www.somesite.com/print.php?mode=3
now trying delete:
http://www.somesite.com/print.php
http://www.somesite.com/print.php?newUser=1
http://www.somesite.com/print.php?mode=1
You can try this:
function removeParamFromUrl($query, $paramToRemove)
{
$params = parse_url($query);
if(isset($params['query']))
{
$queryParams = array();
parse_str($params['query'], $queryParams);
if(isset($queryParams[$paramToRemove])) unset($queryParams[$paramToRemove]);
$params['query'] = http_build_query($queryParams);
}
$ret = $params['scheme'].'://'.$params['host'].$params['path'];
if(isset($params['query']) && $params['query'] != '' ) $ret .= '?'.$params['query'];
return $ret;
}