Is this $string[1] valid PHP? - php

I have coded in PHP for over 10 years and this is the first time I have come across this (legacy code base):
$string = "123456789";
$new_number = $string[1]
$new_number is now 2.
Am I going crazy? I never knew you could add to a string with [x].
EDIT: As many have pointed out, strings in PHP are stored as an array of characters. However, I am right in thinking this is quite unique to PHP? Could you do this in a strongly typed language like C++/C#/Java?

No you don't got crazy. You can access any string within PHP as it would be an array and access each character individual. As you can see here in the manual:
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. [...]

Because a string is effective an array of char's in PHP. This means that you can individually get the characters by accessing the right index. This isnt adding anything really, its just fetching the second character of the string which is '2'. Hope this helps.

Yep! You are not crazy. In PHP you can access the characters in a string by their index. It's treated a lot like an array. You cannot add to the string with $string[] as you would an array, but you can change the value to another character.
$string = "test";
$string[1] = "s";
echo $string; // Echoes 'tsst'

Related

How to get a number from a html source page?

I'm trying to retrieve the followed by count on my instagram page. I can't seem to get the Regex right and would very much appreciate some help.
Here's what I'm looking for:
y":{"count":
That's the beginning of the string, and I want the 4 numbers after that.
$string = preg_replace("{y"\"count":([0-9]+)\}","",$code);
Someone suggested this ^ but I can't get the formatting right...
You haven't posted your strings so it is a guess to what the regex should be... so I'll answer on why your codes fail.
preg_replace('"followed_by":{"count":\d')
This is very far from the correct preg_replace usage. You need to give it the replacement string and the string to search on. See http://php.net/manual/en/function.preg-replace.php
Your second usage:
$string = preg_replace(/^y":{"count[0-9]/","",$code);
Is closer but preg_replace is global so this is searching your whole file (or it would if not for the anchor) and will replace the found value with nothing. What your really want (I think) is to use preg_match.
$string = preg_match('/y":\{"count(\d{4})/"', $code, $match);
$counted = $match[1];
This presumes your regex was kind of correct already.
Per your update:
Demo: https://regex101.com/r/aR2iU2/1
$code = 'y":{"count:1234';
$string = preg_match('/y":\{"count:(\d{4})/', $code, $match);
$counted = $match[1];
echo $counted;
PHP Demo: https://eval.in/489436
I removed the ^ which requires the regex starts at the start of your string, escaped the { and made the\d be 4 characters long. The () is a capture group and stores whatever is found inside of it, in this case the 4 numbers.
Also if this isn't just for learning you should be prepared for this to stop working at some point as the service provider may change the format. The API is a safer route to go.
This regexp should capture value you're looking for in the first group:
\{"count":([0-9]+)\}
Use it with preg_match_all function to easily capture what you want into array (you're using preg_replace which isn't for retrieving data but for... well replacing it).
Your regexp isn't working because you didn't escaped curly brackets. And also you didn't put count quantifier (plus sign in my example) so it would only capture first digit anyway.

Pass a string into an array PHP

I have list of strings like this:
'PYRAMID','htc_europe','htc_pyramid','pyramid','pyramid','HTC','1.11.401.110
CL68035
release-keys','htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys'
It looks like elements of an array,
But when i use
<?php
$string = "'PYRAMID','htc_europe','htc_pyramid','pyramid','pyramid','HTC','1.11.401.110 CL68035 release-keys','htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys'";
$arr = array($string);
print_r($arr);
?>
It doesnt work as I want:
Array ( [0] =>
'PYRAMID','htc_europe','htc_pyramid','pyramid','pyramid','HTC','1.11.401.110
CL68035
release-keys','htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys')
Instead of:
Array ( [0] => PYRAMID, [1] => htc_europe, [2] => htc_pyramid,
...
I dont want to use explode() because my strings are already in array format and many strings have the ',' character.
Please help me, thanks.
Your string is not in an array format. From the way it looks and based on your comments, I would say that you have comma separated values, CSV. So the best way to parse that would be to use functions specifically made for that format like str_getcsv():
$str = "'PYRAMID','htc_europe','htc_pyramid','pyramid','pyramid','HTC','1.11.401.110 CL68035 release-keys','htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys'";
// this will get you the result you are looking for
$arr = str_getcsv($str, ',', "'");
var_dump($arr);
The use of the second and third parameters ensures that it gets parsed correctly also when a string contains a comma.
$string is still a string, so you explode it if you want to make an array out of it.
If your problem is strings have the ',' character, use some other seperator, maybe |
$string = "'PYRAMID'|'htc_europe'|'htc_pyramid'|'pyramid'|'pyramid'|'HTC'|'1.11.401.110 CL68035 release-keys'|'htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys'";
$arr = explode('|',$string);
print_r($arr);
<?php
$int = preg_match_all(
"/'(.+?)'/",
"'PYRAMID','htc_europe','htc_pyramid','pyramid','pyramid','HTC','1.11.401.110 CL68035 release-keys','htc_europe/pyramid/pyramid:4.0.3/IML74K/68035.110:user/release-keys'",
$matches);
print_r($matches[1]);
You can test it here http://micmap.org/php-by-example/en/function/preg_match_all
Due to the edits in the question, my answer is now out of date. I will leave it here because it contains a little explanation why in a particular case explode will be a valid solution.
as you can read in the manual online of php, there is a very precise syntax that can be used when creating an array, this is the reference:
http://php.net/manual/en/function.array.php
As you can see the correct way to use array() to create a new array is declaring each value separated by a comma or by declaring each pair index => value separated by a comma.
There is -no way- to pass a single string to that method (I see it something json like in javascript or java maybe, but this is Off Topic) simply because it won't parse it, the method will take the whole string as is and of course putting it into a single index (that in your case will be index zero).
I am telling you of course to use explode() or split() or to parse your string before, and what I told you before is the reason to my statement.
You probabily want to have each single model of phone in a string inside the array so you will have to remove the single quote first:
$stringReplaced = str_replace("'", "", $yourString);
And then you will have to split the string into an array using:
$array = explode(',',$yourString);
I hope you will take this in consideration
Of course as told by my collegue up there, you can treat this string as a comma separated value and use str_getcsv.
~Though you will need to remove the single quotes to have the pure string.~
(last statement is wrong because you can use the enclosure char param provided by str_getcsv)

How to split a right-to-left string in php

In my php code I need to split an arabic string. However when I copy the string it writes in left to right direction and split function splits the string reversly. Is there a way in php to say that make the string in rtl direction so that it splits correctly?
$text="انا احمد.";
$mysplit = mb_split(' ',$text);
Though your question is bit vague. Seems that array_reverse is what you are looking for.
$text="انا احمد.";
$mysplit = mb_split(' ',$text);
$mysplit = array_reverse($mysplit);
CodeViper Demo.
Actually adding \u200e in front of the string, marks it as left to right.
So then you might be able to split it without needing to reverse the array.
For Right to Left marking the character is \u200f

PHP - Change string really fast

Ok, trying to change a string like so:
[topic]=2[board]=2
to return this instead:
[topic][board]=2
In the above situation, I'll be working with a string variable that equals [topic] and another string variable that equals [topic]=2[board]=2
But this needs to be done for all situations... More examples follow:
profile[area]=account[u]=1
should return this:
profile[area][u]=1
In the above situation, I'll be working with a string variable that equals profile and another string variable that equals profile[area]=account[u]=1
Another example:
moderate[area]=groups[sa]=requests
Should be this:
moderate[area][sa]=requests
In the above situation, I'll be working with a string variable that equals moderate and another string variable that equals moderate[area]=groups[sa]=requests
And another:
[board]=1
Should return:
[board]=1
In the above situation, I'll be working with a string variable that equals [board] and another string variable that equals [board]=1
Basically, what it needs to be able to do, is to get rid of the text in between ONLY the text that are between the brackets of only the first and second brackets (if the second bracket exists only). It should not effect any third, fourth, 5th brackets. Only the first and second brackets.
Can someone please give me a hand with this?
Thanks :)
Here's a regular expression that works:
(?<=\])\=[^\[\r\n]*(?=\[)
http://regexr.com?2vn71
That \r\n might need to be changed to a \Z in PHP, since you won't be dealing with line breaks, but rather with the end of a string.
So, something like:
preg_replace("/(?<=\])\=[^\[\Z]*(?=\[)/", "", $target);
Edit:
Here's a breakdown of what's happening here:
(?<-\]) Make sure there's a [ character before the matched expression
\= Match a = character
[^\[\Z]* Match all characters until you find a [ or the end of the string (\Z)
(?=\[) Make sure there's a [ after the matched expression
Another regex, designed to be used with preg_replace()
preg_replace('/^([a-z]+)?(\[[a-z]+\])(.*)(\[(.*))$/Uis', '$1$2$4', $yourData);

PHP Regex Parse query string containing un-encoded ampersands

I'm receiving a query string (from a terrible payment system whose name I do not wish to sully publicly) that contains un-encoded ampersands
name=joe+jones&company=abercrombie&fitch&other=no
parse_str can't handle this, and I don't know enough of regex to come up with my own scheme (though I did try). My hang up was look-ahead regex which I did not quite understand.
What I'm looking for:
Array
(
[name] => joe jones
[company] => abercrombie&fitch
[other] => no
)
I thought about traipsing through the string, ampersand by ampersand, but that just seemed silly. Help?
How about this:
If two ampersands occur with no = between them, encode the first one. Then pass the result to the normal query string parser.
That should accomplish your task. This works because the pattern for a "normal" query string should always alternate equals signs and ampersands; thus two ampersands in a row means one of them should have been encoded, and as long as keys don't have ampersands in them, the last ampersand in a row is always the "real" ampersand preceding a new key.
You should be able to use the following regex to do the encoding:
$better_qs = preg_replace("/&(?=[^=]*&)/", "%26", $bad_qs);
You could also use the split() function to split the string by ampersands. After that, you could split again each element with the delimeter "="... something like that:
$myarray = split("&", $mystring);
foreach ($myarray as $element) {
$keyvalue = split("=", $element);
$resultarray[$keyvalue[0]] = $keyvalue[1];
}
print_r($resultarray);
Not tested! But you should get the idea.

Categories