PHP Get dynamic value from string - php

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(*)'.

Related

How to find certain text within a php variable and then replace all text between characters either side

I have a variable within PHP coming from a form that contains email addresses all separated by a comma (')
For example:
user#domain1.com,user#domain2.com,user3#domain2.com,user2#domain4.com
What I am trying to achieve is to look at the variable, find for example #domain2.com and remove everything between the comma that are either side of that email.
I know I can use str_replace to replace just the text I'm after, like so:
$emails=str_replace("#domain2.com", "", "$emailscomma");
However, I'm more looking to remove that entire email based on the text I'm asking it to find.
So in this example I'm wanting to remove user#domain2.com and user3#domain2.com
Is this possible?
Searched any articles I could find but couldn't find something that finds something and then replaces but more than just the text it finds.
You can of course use regular expressions, but I would suggest a bit easier way. Operating on arrays is much easier than on strings and substrings. I would convert your string to an array and then filter it.
$emails = "user#domain1.com,user#domain2.com,user3#domain2.com,user2#domain4.com";
// Convert to array (by comma separator)
$emailsArray = explode(',', $emails);
$filteredArray = array_filter($emailsArray, function($email) {
// filters out all emails with '#domain2.com' substring
return strpos($email, '#domain2.com') === false;
});
print_r($filteredArray);
Now you can convert the filtered array to string again. Just use implode() function.

regex to explode a string json into values

I try build a php regex that validate this type of input string:
{name:'something name here',type:'',id:''},{name:'other name',type:'small',id:34},{name:'orange',type:'weight',id:28}
etc...
So, it is a list of json that each contain 3 field: name,type,id.Field name is always present, instead type and id can be together empty string ( '' ). Then I can explode it by comma if it has valid format and obtain a array of json string.
How can I do?
UPDATE
it isn't a valid json as you can say but I have a input field where user put tags, and I want track a name, type and id of that tags.
example:
tag1 (has name,type,id), tags2 (has only name), tags3(has name, type,id).
So, I think that I can post a string in that format:
{'name':'test','type':'first','id':3},{'name':'other','type':'second','id':45}, etc
But I must validate this string with a regex. I can do
$data = explode(',',$list);
and then I do:
foreach($data as $d){
$tmp = json_decode($d);
if($tmp == false) echo 'error invalid data';
}
As Gubo pointed out: this is not a valid JSON encoded string. If the actual data you want to process in your script ís valid however, you're barking up the wrong tree looking for a regular expression... PHP has tons of functions that will parse JSON strings much faster than a regular expression.
$string1 = "{name:'something name here',type:'',id:''},{name:'othername',type:'small',id:34},{name:'orange',type:'weight',id:28}";
$string2 = '[{"name":"something name here","type":"","id":""},{"name":"othername","type":"small","id":"34"},{"name":"orange","type":"weight","id":"28"}]';
Where $string2 is the data in valid JSON formar. If your data is a valid JSON string, the following code will suffice:
$parsed = json_decode($string2);
//$parsed[0]['name'] return 'something name here'
If, however you're dealing with invalid JSON strings, things get a bit more complicated... First off: if you're lacking your object properties (or array keys as they will become in PHP) are quoted, a quick fix would be this:
$parsed = json_decode('['.$string1.']');
If you really want to parse them seperatly:
$separated= preg_split('/(?<=[\}]),/',$string1);
But I can't see why you would want to do that. The biggest issue here is the absence of quotes on the property strings (or keys). I have put together a regex (untested) that could quote those strings:
$parsed = json_decode(preg_replace('/(?<=[\{,])([a-z]+)/',str_replace('\'','"',$string1)));
Keep in mind, the last regex is untested, so it might not perform as you expect it to... but it should help you on your way... for the last example, the same rules apply for all the other examples I gave: if the quotes and brackets are there, just use json_decode, if the brackets are missing, add them, too...
It's getting rather late here, so I'm off to bed now... I hope this answer isn't packed with typo's and sentences that nobody can understand. If it is, I do apologize.
You don't need a regex for that. Just use this:
var_dump(json_decode($json, true));
See: http://us.php.net/manual/en/function.json-decode.php

PHP key=value string to array

I have a string category=45&format=1 that I want to convert into a key=value array.
Does anyone know if there is a quick way of doing this without having to write a function that explode's the & and then the = * snore *
Since you're dealing with the URL query format: parse_str
parse_str('category=45&format=1', $array);
http://php.net/parse_str
If it's a query string or doesn't contain special characters you can use parse_str.

php string manipulation nonrandom sort

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.

how to get words from html in an array using php?

<?php
$html = file_get_contents('http://hypermedia.ids-mannheim.de/');
?>
this code returns me the html of the website in a string. How do I separate the string into different words? After getting the individual words in an array I would like to detect which one is in German...
$words = explode(' ', strip_tags($html));
or
$words = preg_split("/[\s,]+/", strip_tags($html));
The second one will consider not just the space character as a delimiter, but tabs and commas as well.
work with a regex, something like this
#([\w]+)#i
A code example:
if(preg_match_all('#([\w]+)\b#i', $text, $matches)) {
foreach($matches[1] as $key => $word) {
echo $word."\n";
}
}
Then you have to compare each with some kind of dictionary.
I think you need to separate your problem into steps.
First parse your returned html string to find which part is html tags and structure. You can use DOM for such purpose.
Then, you can separate your innerHTML data from tags and split innerHTML text into tokens to obtain an array. Dunno the best way but a simple array regex split can do the job.
The interesting part of finding german words, could be done matching your wordlist against a dictionary, again using arrays or maps.. or, better, using a DB (SQLlite maybe could be better than a real rdbms like mysql)..

Categories