Adding something to the start of a variable? - php

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);
?>

Related

Parse variables in PHP string

NOTE: Eval is used here in total knowledge, the string parsed is entered by an administrator only, and the purpose is to store instructions in database, without restrictions to the instructions.
If you have a good alternative, it is always appreciated, but don't just say "eval is bad".
I have a String in PHP, for example
$myString = "(35*$var1*64)/$var2";
I want to eval() this string, but before, I want to modify all the variables in the string like this:
$var2 -> $_POST['var2']
There may or may not be a blank space after the variable in $myString .
When I eval $myString, PHP throws an error "Undefined variable $var1". PHP read the string and parse the variables, so I guess there should be a way to parse all the variables in the string.
The output should be:
$myStringParsed = "(35*$_POST['var1']*64)/$_POST['var2']";
or an equivalent.
Not maybe the best solution, but you can preprocess $_POST variable and generate $variablesString like this:
$variablesString = '';
foreach($_POST as $key => $val) {
$variablesString .= '$' . $key . ' = ' . $val . ';' . PHP_EOL;
}
eval($variablesString . PHP_EOL . $myString)
For string support you can check if $val is string, and if yes - wrap it with quotes.
Second way
$myString = 'return (35 * $var1 * 64) / $var2;';
$re = "/\\$(\\w*)/im";
preg_match_all($re, $myString, $matches);
foreach($matches[1] as $match) {
$search = '$' . $match;
$replace = '$_POST[\'' . $match . '\']';
$myString = str_replace($search, $replace, $myString);
}
echo eval($myString);
You can check it here
Assuming you mean....
$myString = '(35*$var1*64)/$var2';
The a more robust solution (consider $myvar10) than that suggested by ASGM is:
$replace=array(
'/\b\$var1\b/'=>$_POST['var1'],
'/\b\$var2\b/'=>$_POST['var2'],
...
);
$interpolated=preg_replace(array_keys($replace)
, $replace, $myString);
Note that I would recommend that you interpolate the string with literals rather than substituting one place holder for another. In addition to eliminating unnecessary processing, it also means you can check the content of the resulting string to ensure it only contains digits and operators (and a restricted number of functions if appropriate).
You are using wrong string enclosing quotes. Use '(35*$var1*64)/$var2':
//$var1 = $_POST['var1'];
//$var2 = $_POST['var2'];
$var1 = '10';
$var2 = '20';
$myString = 'return (35 * $var1 * 64) / $var2;';
echo eval($myString);
//1120
Working example of eval
If you want to take any variable from POST, than you can use extract() to get array keys as variables with associated values:
<?php
// Change it to real $_POST
$POST = [
'var1' => '10',
'var2' => '20',
];
extract($POST, EXTR_SKIP);
$myString = 'return (35 * $var1 * 64) / $var2;';
echo eval($myString);

PHP - How to add a specific character at the end of a string?

I am looking for hours how can i add an specific character at the end of a string.
Here is my code:
$string = "I have a";
$AddToEnd = "]";
I want to make AddToEnd to appear after the last character in $string.
How it is possible, thanks in advance!
See PHP's String Operators to see how to concatenate strings:
$finalString = $string . $AddToEnd;
// OR
$string .= $AddToEnd
You can also use a function like implode():
$finalString = implode(array($string, $AddToEnd));
What you're looking for is called concatenation.
In PHP you have ms to do that :
$concat = $string . $AddToEnd;

How to make the first 2 characters of a string uppercase?

How can I use the PHP strtoupper function for the first two characters of a string? Or is there another function for that?
So the string 'hello' or 'Hello' must be converted to 'HEllo'.
$txt = strtoupper( substr( $txt, 0, 2 ) ).substr( $txt, 2 );
This works also for strings that are less than 2 characters long.
$string = "hello";
$string{0} = strtoupper($string{0});
$string{1} = strtoupper($string{1});
var_dump($string);
//output: string(5) "HEllo"
Assuming it's just a single word you need to do:
$ucfirsttwo = strtoupper(substr($word, 0, 2)) . substr($word, 2);
Basically, extract the first two characters and uppercase the, then attach the remaining characters.
If you need to handle multiple words in the string, then it gets a bit uglier.
Oh, and if you're using multi-byte characters, prefix the two functions with mb_ to get a multibyte-aware version.
$str = substr_replace($str, strtoupper($str[0].$str[1]), 1, 2);
Using preg_replace() with the e pattern modifier could be interesting here:
$str = 'HELLO';
echo preg_replace('/^(\w{1,2})/e', 'strtoupper(\\1)', strtolower($str));
EDIT: It is recommended that you not use this approach. From the PHP manual:
Use of this modifier is discouraged, as it can easily introduce security vulnerabilites:
<?php
$html = $_POST['html'];
// uppercase headings
$html = preg_replace(
'(<h([1-6])>(.*?)</h\1>)e',
'"<h$1>" . strtoupper("$2") . "</h$1>"',
$html
);
The above example code can be easily exploited by passing in a string
such as <h1>{${eval($_GET[php_code])}}</h1>. This gives the attacker
the ability to execute arbitrary PHP code and as such gives him nearly
complete access to your server.
To prevent this kind of remote code execution vulnerability the
preg_replace_callback() function should be used instead:
<?php
$html = $_POST['html'];
// uppercase headings
$html = preg_replace_callback(
'(<h([1-6])>(.*?)</h\1>)',
function ($m) {
return "<h$m[1]>" . strtoupper($m[2]) . "</h$m[1]>";
},
$html
);
As recommended, instead of using the e pattern, consider using preg_replace_callback():
$str = 'HELLO';
echo preg_replace_callback(
'/^(\w{1,2})/'
, function( $m )
{
return strtoupper($m[1]);
}
, strtolower($str)
);
This should work strtoupper(substr($target, 0, 2)) . substr($target, 2) where $target is your 'hello' or whatever.
ucfirstDocs does only the first, but substr access on strings works, too:
$str = ucfirst($str);
$str[1] = strtoupper($str[1]);
Remark: This works, but you will get notices on smaller strings if offset 1 is not defined, so not that safe, empty strings will even be converted to array. So it's merely to show some options.

How to convert a string with numbers and spaces into an int

I have a small problem. I am tryng to convert a string like "1 234" to a number:1234
I cant't get there. The string is scraped fro a website. It is possible not to be a space there? Because I've tried methods like str_replace and preg_split for space and nothing. Also (int)$abc takes only the first digit(1).
If anyone has an ideea, I'd be greatefull! Thank you!
This is how I would handle it...
<?php
$string = "Here! is some text, and numbers 12 345, and symbols !£$%^&";
$new_string = preg_replace("/[^0-9]/", "", $string);
echo $new_string // Returns 12345
?>
intval(preg_replace('/[^0-9]/', '', $input))
Scraping websites always requires specific code, you know how you receive the input - and you write code that is required to make it usable.
That is why first answer is still str_replace.
$iInt = (int)str_replace(array(" ", ".", ","), "", $iInt);
$str = "1 234";
$int = intval(str_replace(' ', '', $str)); //1234
I've just came into the same issue, however the answer that was provided wasn't covering all the different cases I had...
So I made this function (the idea popped in my mind thanks to Dan) :
function customCastStringToNumber($stringContainingNumbers, $decimalSeparator = ".", $thousandsSeparator = " "){
$numericValues = $matches = $result = array();
$regExp = null;
$decimalSeparator = preg_quote($decimalSeparator);
$regExp = "/[^0-9$decimalSeparator]/";
preg_match_all("/[0-9]([0-9$thousandsSeparator]*)[0-9]($decimalSeparator)?([0-9]*)/", $stringContainingNumbers, $matches);
if(!empty($matches))
$matches = $matches[0];
foreach($matches as $match):
$numericValues[] = (float)str_replace(",", ".", preg_replace($regExp, "", $match));
endforeach;
$result = $numericValues;
if(count($numericValues) === 1)
$result = $numericValues[0];
return $result;
}
So, basically, this function extracts all the numbers contained inside of a string, no matter how many text there is, identifies the decimal separator and returns every extracted number as a float.
One can specify what decimal separator is used in one's country with the $decimalSeparator parameter.
Use this code for removing any other characters like .,:"'\/, !##$%^&*(), a-z, A-Z :
$string = "This string involves numbers like 12 3435 and 12.356 and other symbols like !## then the output will be just an integer number!";
$output = intval(preg_replace('/[^0-9]/', '', $string));
var_dump($output);

Increment integer at end of string

I have a string, "Chicago-Illinos1" and I want to add one to the end of it, so it would be "Chicago-Illinos2".
Note: it could also be Chicago-Illinos10 and I want it to go to Chicago-Illinos11 so I can't do substr.
Any suggested solutions?
Complex solutions for a really simple problem...
$str = 'Chicago-Illinos1';
echo $str++; //Chicago-Illinos2
If the string ends with a number, it will increment the number (eg: 'abc123'++ = 'abc124').
If the string ends with a letter, the letter will be incremeted (eg: '123abc'++ = '123abd')
Try this
preg_match("/(.*?)(\d+)$/","Chicago-Illinos1",$matches);
$newstring = $matches[1].($matches[2]+1);
(can't try it now but it should work)
$string = 'Chicago-Illinois1';
preg_match('/^([^\d]+)([\d]*?)$/', $string, $match);
$string = $match[1];
$number = $match[2] + 1;
$string .= $number;
Tested, works.
explode could do the job aswell
<?php
$str="Chicago-Illinos1"; //our original string
$temp=explode("Chicago-Illinos",$str); //making an array of it
$str="Chicago-Illinos".($temp[1]+1); //the text and the number+1
?>
I would use a regular expression to get the number at the end of a string (for Java it would be [0-9]+$), increase it (int number = Integer.parse(yourNumberAsString) + 1), and concatenate with Chicago-Illinos (the rest not matched by the regular expression used for finding the number).
You can use preg_match to accomplish this:
$name = 'Chicago-Illinos10';
preg_match('/(.*?)(\d+)$/', $name, $match);
$base = $match[1];
$num = $match[2]+1;
print $base.$num;
The following will output:
Chicago-Illinos11
However, if it's possible, I'd suggest placing another delimiting character between the text and number. For example, if you placed a pipe, you could simply do an explode and grab the second part of the array. It would be much simpler.
$name = 'Chicago-Illinos|1';
$parts = explode('|', $name);
print $parts[0].($parts[1]+1);
If string length is a concern (thus the misspelling of Illinois), you could switch to the state abbreviations. (i.e. Chicago-IL|1)
$str = 'Chicago-Illinos1';
echo ++$str;
http://php.net/manual/en/language.operators.increment.php

Categories