php string manipulation nonrandom sort - php

I am trying to sort a 4 character string thats being feed in from a user into a different order. an example might be they type "abcd" which I then take and turn it into "bcad".
Here is an example of my attempt which is not working :P
<?php
$mixedDate = $_REQUEST['userDate'];
$formatted_date = firstSubString($mixedDate,2).secondSubString($mixedDate,3).thirdSubString($mixedDate,1).fourthSubString($mixedDate,4);
//... maybe some other stuff here then echo formatted_date
?>
any help would be appreciated.

Copied from comment:
You could pretty simply do this by doing something like:
$formatted_date = $mixedDate[1].$mixedDate[2].$mixedDate[0].$mixedDate[3];
That way, you don't have to bother with calling a substring method many times, since you're just moving individual characters around.

<?php
$mixedDate = $_REQUEST['userDate'];
$formatted_date = $mixedDate{1}.$mixedDate{2}.$mixedDate{0}.$mixedDate{3};
echo $formatted_date;
?>
The curly syntax allows you to get just that one character from your string.
It should be noted that this works correctly on your sample string, abcd and turns it into bcad if $_REQUEST['userDate'] is abcd.

Look into split() in php. It takes a string and a delimiter then splits the string into an array. Either force the user to use a certain format or use a regex on the input string to put the date into a known format, like dd/mm/yyyy or dd-mm-yyyy, then use the hyphen or / as the delimiter.
Once the string is split into an array, you can rearrange it any way you like.

That is very simple.
If
$mixedDate = 21-12-2010
then, try this
echo substr($mixedDate, 3,
2).'-'.substr($mixedDate, 0,
2).'-'.substr($mixedDate, 6);
this will result in
12-21-2010
This is assuming the format is fixed.

Use str_split() to break the string into single characters:
$char_array = str_split($input_string);
If you know exactly what order you want, and you only have four characters, then from here you can actually just do it the way you wanted from your question, and concatenate the array elements back into a single string, like so:
$output_string = $char_array[2].$char_array[3].$char_array[1].$char_array[4];
If your needs are more complex, you can sort and implode the string:
Use sort() to put the characters into order:
sort($char_array);
Or one of the other related sorting functions that PHP provides if you need a different sort order. If you need an sort order which is specific to your requirements, you can use usort(), which allows you to write a function which defines how the sorting works.
Then re-join the characters into a single string using implode():
$output_string = implode($char_array);
Hope that helps.

Related

PHP Get dynamic value from string

I'm trying to get a dynamic value from a string. But nothing shows up.
ob_start();
var_dump($torrent->result['info']['pieces']);
$pieces = ob_get_clean();
$piecescorrected = explode($pieces, 'string(*)');
echo $piecescorrected;`
Whats up with this?
Edit:
Some clarification.
$pieces needs to be filter from all the other random characters after it.
Output of $pieces:
string(12620) "< ÏÚÿÊܵ䬧âW—µ-‘CÄÞ½§§¼ø0LØëÍI­×L —#c õL2“iÓ¹ý¼Bl'-“’4žþÊYï‡
Now $pieces needs to be corrected by filtering out string(12620)
But the value is dynamic so therefore I used $piecescorrected = explode($pieces, 'string(*)');
Mind the * in string(*)
As it turned out in the comments you actually wanted just the string length.
So you don't need any output buffering or explode() calls. Just use strlen() like this:
echo strlen($torrent->result['info']['pieces']);
output:
12620
This is what's up with it: explode() is looking for a literal string. It doesn't take wildcards.
If you had a string like 1,2,3,4 you could use explode(',', '1,2,3,4') to get an array of those values by splitting on comma. Here, you could split on the literal 'string' but not 'string(*)'.

PHP - replace php formula

I am trying to work out the optimal way to replace all PHP variables within a string of code with a call to an array instead as shown below.
E.g. source code string
$random_var_name + $random_var_name2 * $diff_var_name3
Transformed into
$varArray["random_var_name"] + $varArray["random_var_name2"] * $varArray["diff_var_name3"]
I had thought that preg_replace() was the optimal solution, but the difficulty comes with the need to perform the replacement with a sub-part of the search pattern.
Perhaps it is better to just retrieve all the variables with a preg_match, edit/wrap them, then perform a single str_replace() for each variable?
However this is probably considerably slower.
The following regex should do what you're asking:
preg_replace('/\$([a-zA-Z_0-9]+)/', '$varArray["$1"]', $input_string);
In order to avoid to change $var['foo'] to $varArray["var"]['foo'] you have to check there're no [ character after the variable name. For this use a negative look-ahead:
$string = preg_replace('/\$(\w+)(?![\w\[])/', '$varArray["$1"]', $string);

Number_format for arabic/persian numbers

I have a "price" field in a mysql database, which contains the price of a product in arabic or persian numbers.
Example of number: ۱۲۳۴۵۶۷۸۹۰ //1234567890
I cannot figure out how to format this so that it is formatted in a user-friendly way.
By that I mean, grouped by thousands or something similiar.
This would be ideal: ۱ ۲۳۴ ۵۶۷ ۸۹۰
number_format in php is what I would have used on latin numbers.
Is there any function which I don't know about, to make this possible?
If not, ideas of how to create one is appreciated.
Thanks
You could use a regex like this:
([۱۲۳۴۵۶۷۸۹۰])(?=(?:[۱۲۳۴۵۶۷۸۹۰]{3})+$)
Search and replace with \1, on the string ۱۲۳۴۵۶۷۸۹۰ would give you ۱,۲۳۴,۵۶۷,۸۹۰ (using , instead of space since SO trims them off. But using space in the replace instead will work just as well).
I would have to agree with the suggestion in the comments though, store the data using the numeric types available and convert them on input/output.
If you can store numbers in your database instead of strings (or convert to ascii numbers), then standard currency formatting with group-separators can be done with php5-intl functions. You just need ISO locale and currency codes:
$nf = new \NumberFormatter('fa_IR', \NumberFormatter::CURRENCY);
echo $nf->formatCurrency(1234.1234, 'IRR');
۱٬۲۳۴ ﷼
Otherwise, #rvalvik's answer is good.
See http://php.net/manual/en/class.numberformatter.php
More elegantly written than #rvalvik's regex pattern, you can add a comma after a character that is followed by 3, 6, 9, etc. characters.
Code: (Demo)
$str = '۱۲۳۴۵۶۷۸۹۰';
var_export(
preg_replace(
'~.\K(?=(?:.{3})+$)~u',
",",
$str
)
);
Output:
'۱,۲۳۴,۵۶۷,۸۹۰'
Here is similar answer to a related question.

Capture a date from an unknow string length

I have a string say "ETS 13-JUN-13sf342356". I am able to parse out the date with some simple ltrim and rtrim functions. My question is if I don't know what is before or after or how long the string is can I still capture this date? Some more examples are:
"JoeR13JUN134092883094"
"CC13-JUN-13tl320994"
"3425313-JUN-13tl345550"
Is there a single function that will always capture the (in this case) 13-JUN-13 date out of these strings?
I tried the following with your input and worked for that. Seems long but give it a try:
([0-9]{2})(\-[A-Z]+|[A-Z]+)(\-[0-9]{2}|[0-9]{2})

PHP Regex string returns two identical arrays

I've got a Regex query here to pull out all of the tags in a page. It looks like this:
preg_match_all('%<tr[^>]++>(.*?)</tr>%s', $pageText, $rows);
Problem is that while it does find all of the tags on the page in the return array it actually returns a multidimensional array, where each entry of the first array contains an array of all of the matches. In other words, it hands me multiple identical copies of the first array, IE the one I actually want.
Help please?
EDIT: Also relevant: I'm not allowed to use DOM for this application despite it being a significantly easier (and better) way of going about things.
What you're actually asking about is the $row[0] list, which redundantly contains the <tr>...</tr> blob again. If you just care about the (.*?) inner data, then use \K to reset the full match.
preg_match_all('=<tr\b[^>]*+>(.*?)</tr>\K=s', $pageText, $rows);
It's not possible to get rid of $row[0] completely. You'll have to ignore it, and use $row[1] alone.
Try this one:
preg_match_all('~<tr(?:\\s+[^>]*)?>(.*?)</tr>~si', $pageText, $rows);
var_dump($rows[1]);
Don't use % to wrap RegExps. It's a character somehow reserved for printf() like functions and with %s or %i at the end of your Pattern, it can be quite confusing.

Categories