My PHP Code:
$username="jack";
$var= mt_rand(1000,100000 );
$data="$username _Deleted_$var";
echo $data;
Expected Output: jack_Deleted_91111
Original Output: jack _Deleted_91111
$data = "{$username}_Deleted_$var";
or
$data = $username."_Deleted_".$var;
. is in php symbol for concatenating strings, { and } used in string means that anything between this symbol is a variable.
Try this:
$data=$username . '_Deleted_' . $var;
See, if that solves your white space issue.
Related
I have a question which relates to PHP. Is there any way to just grab the last string using a delimiter?
For example, to put you in perspective, I want to grab the lastest content from the / from every string.
/folder1/blabla/important
/folder2/blabla/blabla/bla/important2
How could I using PHP cut the whole string and get only the latest value. The output would be something like:
/important
/important2
I have tried regex but I am not very good at it,
MY CODE:
$var = 'goldfe/sfksfksk/admadmadmam/akdmasdkasm/red';
echo $var . '<br>';
$varPretty = explode('/', $var);
echo $varPretty[-1];
Here the $varPretty[-1] should return red.
ANOTHER SOLUTION IS:
$var = 'goldfe/sfksfksk/admadmadmam/akdmasdkasm/red';
echo $var . '<br>';
$varPretty = explode('/', $var);
echo end($varPretty);
Please try this method will work for you:
$txt = "/folder1/blabla/important";
echo substr($txt, strrpos($txt, '/') + 1);
Output should be like:
important
I am looking for some code that allows you to add +44 onto the beginning of my $string variable.
So the ending product would be:
$string = 071111111111
+44071111111111
Your $string variable isn't actually a string in this scenario; it's an integer. Make it a string by putting quotes around it:
$string = "071111111111"
Then you can use the . operator to append one string to another, so you could do this:
$string = "+44" . $string
Now $string is +44071111111111. You can read more about how to use the . (string concatenation operator) on the PHP documentation here.
Other people's suggestions of just keeping $string as an integer wouldn't work: "+44" . 071111111111 is actually +447669584457. Due to the 0 at the start of the number, PHP converts it to an octal number rather than a decimal one.
You can combine strings by .
$string = '+44'.$string;
You can use universal code, which works with another parameters too.
<?php
$code = "+44";
$string = "071111111111";
function prepend(& $string, $code) {
$test = substr_replace($string, $code, 0, 0);
echo $test;
}
prepend($string, $code);
?>
$i = $result->fetch_assoc();
preg_replace("/\{(.*?)\}/", $i["$1"], $content);
Error - Undefined variable: $1
// $1 - 'string'; // result search preg_replace()
// $i['string'] = 'hello';
How right syntax will be for print 'hello'?
ok next time please spend a little more time on asking the question:
<?php
$i['string'] = 'zzzzzzzzzzzzzzzzzzzzzz';
$content = "test test test {string} testtesttesttesttest";
$x=preg_replace_callback("/\{(.*?)\}/", function($m) use($i){
return $i[$m[1]];
}, $content);
echo $x;
demo: http://codepad.viper-7.com/u29uKh
for this particular approach you need to use preg_replace_callback() requires PHP 5.3+
You can make your replacements faster using strtr. To do that, you only need an associative array, but this time, all keys must be enclosed between curly brackets.
$i = $result->fetch_assoc();
$keys = array_map(function($k) { return '{' . $k . '}'; }, array_keys($i));
$trans = array_combine($keys, $i);
$content = strtr($content, $trans);
A variable name can't start with a number in PHP. It must start with an underscore or letter.
Basically I have a block of html that I want to echo to the page and the html has the $ sign in it and the php thinks it is a variable so $1 is treated as the variable not the value and is not displayed.
There is the standard answers here but none are working: PHP: How to get $ to print using echo
My next idea is to split the string at the $ and echo each part out.
Here is the code I have tried echo and print.
foreach ($rows as $rowmk) {
$s = $rowmk->longdescription;
//$s = str_replace('$', '#', $s);
$s = str_replace('$', '\$', $s);
//echo "$s" . "<br>";
print $s;
}
All help appreciated.
OK I solved by using the character code value for $
foreach ($rows as $rowmk) {
$s = $rowmk->longdescription;
$s = str_replace('$', '$', $s);
echo $s . "<br>";
}
I figured I should just post it anyway.
Thanks,
Mat
Or you could echo string literal using single quotes...
<?php
echo 'Give me $1';
?>
will print:
Give me $1
PHP string docs:
http://php.net/manual/en/language.types.string.php
Side note - the link you provide has many answers that would work perfectly. How are you applying them in a way that doesn't work?
Just use a single quoted string.
$foo = 'Hello';
echo '$foo'; // $foo
echo "$foo"; // Hello
You're doing it in the wrong place. Variable interpolating is done when double quoted string literal (which in your case is stored within $rowmk->longdescription is daclared. Once it's done, you can't really do anything to get your $s back.
Solution, do proper escaping, when you declare the string.
I assume you read your rows from a database. Dollar Signs inside these strings will not be interpolated by php. Here's a little test script to try it out:
// you'd first have to set the three variables according to your database
$dbh = new PDO($DSN, $DB_USER, $DB_PASS);
// create a table and insert a string containing a dollar sign
$dbh->exec('CREATE TABLE IF NOT EXISTS some_text ( longdescription VARCHAR( 255 ))');
$dbh->exec('INSERT INTO some_text ( longdescription ) VALUES ( "10 $" )');
// query all the data from the table
$query =$dbh->query("SELECT * FROM some_text");
$rows = $query->fetchAll(PDO::FETCH_CLASS);
// loop over all the rows (as in your example) and output the rows
// no problem at all
foreach ($rows as $rowmk) {
$s = $rowmk->longdescription;
echo $s . "<br>";
}
You can use "\$"
ex:
"\$stringvalue"
I did it using this
echo "$" . "VariableName";
If I have a string
00020300504
00000234892839
000239074
how can I get rid of the leading zeroes so that I will only have this
20300504
234892839
239074
note that the number above was generated randomly.
ltrim:
$str = ltrim($str, '0');
(string)((int)"00000234892839")
you can add "+" in your variable,
example :
$numString = "0000001123000";
echo +$numString;
Similar to another suggestion, except will not obliterate actual zero:
if (ltrim($str, '0') != '') {
$str = ltrim($str, '0');
} else {
$str = '0';
}
Or as was suggested (as of PHP 5.3), shorthand ternary operator can be used:
$str = ltrim($str, '0') ?: '0';
Don't know why people are using so complex methods to achieve such a simple thing! And regex? Wow!
Here you go, the easiest and simplest way (as explained here: https://nabtron.com/kiss-code/ ):
$a = '000000000000001';
$a += 0;
echo $a; // will output 1
Regex was proposed already, but not correctly:
<?php
$number = '00000004523423400023402340240';
$withoutLeadingZeroes = preg_replace('/^0+/', '', $number)
echo $withoutLeadingZeroes;
?>
output is then:
4523423400023402340240
Background on Regex:
the ^ signals beginning of string and the + sign signals more or none of the preceding sign. Therefore, the regex ^0+ matches all zeroes at the beginning of a string.
I don't think preg_replace is the answer..
old thread but just happen to looking for this today. ltrim and (int) casting is the winner.
<?php
$numString = "0000001123000";
$actualInt = "1123000";
$fixed_str1 = preg_replace('/000+/','',$numString);
$fixed_str2 = ltrim($numString, '0');
$fixed_str3 = (int)$numString;
echo $numString . " Original";
echo "<br>";
echo $fixed_str1 . " Fix1";
echo "<br>";
echo $fixed_str2 . " Fix2";
echo "<br>";
echo $fixed_str3 . " Fix3";
echo "<br>";
echo $actualInt . " Actual integer in string";
//output
0000001123000 Origina
1123 Fix1
1123000 Fix2
1123000 Fix3
1123000 Actual integer in tring
A short hack can be to use round() it will remove leading zeros.
echo round('00020300504'); //20300504
Ajay Kumar offers the simplest echo +$numString;
I use these:
echo round($val = "0005");
echo $val = 0005;
//both output 5
echo round($val = 00000648370000075845);
echo round($val = "00000648370000075845");
//output 648370000075845, no need to care about the other zeroes in the number
//like with regex or comparative functions. Works w/wo single/double quotes
Actually any math function will take the number from the "string" and treat it like so. It's much simpler than any regex or comparative functions.
I saw that in php.net, don't remember where.
Im Fixed with this way.
its very simple. only pass a string its remove zero start of string.
function removeZeroString($str='')
{
while(trim(substr($str,0,1)) === '0')
{
$str = ltrim($str,'0');
}
return $str;
}
Assuming you want a run-on of three or more zeros to be removed and your example is one string:
$test_str ="0002030050400000234892839000239074";
$fixed_str = preg_replace('/000+/','',$test_str);
You can make the regex pattern fit what you need if my assumptions are off.
This help?