Cleaning data and removing brackets - php

Okay I have been having a little issue with the code below right now it pulls a bunch of data about a few stocks for me but I cant seem to get ride of the [ or ]. I thought it would be easy to remove the brackets by adding them to the end and the beginning of the preg_split but right when I do it just pops a error message.
Is there any command to remove all [ or all ] cause I know I have found a command in the past to remove all non numeric characters thank you so much btw
<?php
$Bloomberg = 'http://www.bloomberg.com/quote/AAPL:US';
$Bloomberghtml = file_get_contents($Bloomberg);
$BloombergStart = preg_split('/data_values":/',$Bloomberghtml);
$BloombergRawData = preg_split('/>/',$BloombergStart[1]);
$OpenTimeStart = preg_split('/exch_open_time":/',$BloombergRawData[0]);
$OpenTime = preg_split('/,"/',$OpenTimeStart[1]);
$CloseTimeStart = preg_split('/exch_close_time":/',$BloombergRawData[0]);
$CloseTime = preg_split('/,"/',$CloseTimeStart[1]);
$StartPriceData = preg_split('/,/',$BloombergRawData[0]);
echo $BloombergRawData[0];
echo "<br><br><br>";
echo $OpenTime[0];
echo "<br>";
echo $CloseTime[0];
echo "<br>";
print_r($StartPriceData);
?>

I'm not sure I fully understood your problem, but if you need to remove the '[' and ']' chars you can do that rather simply:
str_replace(array( '[', ']' ), '', $BloombergRawData);
Not the most elegant solution, but it should to the trick.

Related

Double quoted nested array won't work

Consider this :
$a = 'u';
$b[$a] = 'v';
$c[$b[$a]] = 'w';
This works fine:
php > echo $c[$b[$a]];
w
This also works:
php > echo '$c[$b[$a]]';
'$c[$b[$a]]'
However this leads to a syntax error:
php > echo "$c[$b[$a]]";
PHP Parse error: syntax error, unexpected '[', expecting ']'
While a shorter version works:
php > echo "$b[$a]";
v
Why?
In a double quoted string there are two kinds of variable parsing, simple and complex. Simple parsing will only work with a single dimensional array or object. So these will work:
echo "Valid: $foo[1]";
echo "Valid: $foo[bar]";
echo "Valid: $foo->bar";
But these will not:
echo "Invalid: $foo[1][2]";
echo "Invalid: $foo->bar->baz";
echo "Invalid: $foo->bar()[2]";
Complex parsing is what halfer suggested in his answer, which wraps the expression in curly braces, and will indeed solve your problem:
echo "Valid: ${foo[1][2]}";
echo "Valid: ${foo->bar->baz}";
echo "Valid: ${foo->bar()[2]}";
The short answer is: don't write PHP like this! If it is confusing to read then use an intermediate variable.
However, it can be fixed: it looks like PHP just wants the brace delimiters at the outermost edges of the variable:
<?php
$a = 'u';
$b[$a] = 'v';
$c[$b[$a]] = 'w';
echo "{$c[$b[$a]]}";
This is also fine as well:
echo "${c[$b[$a]]}";
In the first case, the whole thing is wrapped in braces, and in the second, the $ is allowed outside of the brace construct to say that the next bit is a variable.

Regex - the difference in \\n and \n

Sorry to add another "Regex explanation" question to the internet but I must know the reason for this. I have ran this regex through RegexBuddy and Regex101.com with no help.
I came across the following regex ("%4d%[^\\n]") while debugging a time parsing function. Every now and then I would receive an 'invalid date' error but only during the months of January and June. I mocked up some code to recreate exactly what was happening but I can't figure out why removing the one slash fixes it.
<?php
$format = '%Y/%b/%d';
$random_date_strings = array(
'2015/Jan/03',
'1985/Feb/13',
'2001/Mar/25',
'1948/Apr/02',
'1948/May/19',
'2020/Jun/22',
'1867/Jul/09',
'1901/Aug/11',
'1945/Sep/21',
'2000/Oct/31',
'2009/Nov/24',
'2015/Dec/02'
);
$year = null;
$rest_of_string = null;
echo 'Bad Regex:';
echo '<br/><br/>';
foreach ($random_date_strings as $date_string) {
sscanf($date_string, "%4d%[^\\n]", $year, $rest_of_string);
print_data($date_string, $year, $rest_of_string);
}
echo 'Good Regex:';
echo '<br/><br/>';
foreach ($random_date_strings as $date_string) {
sscanf($date_string, "%4d%[^\n]", $year, $rest_of_string);
print_data($date_string, $year, $rest_of_string);
}
function print_data($d, $y, $r) {
echo 'Date string: ' . $d;
echo '<br/>';
echo 'Year: ' . $y;
echo '<br/>';
echo 'Rest of string: ' . $r;
echo '<br/>';
}
?>
Feel free to run this locally but the only two outputs I'm concerned about are the months of June and January. "%4d%[^\\n]" will truncate $rest_of_string to /Ju and /Ja while "%4d%[^\n]" displays the rest of the string as expected (/Jan/03 & /Jun/22).
Here's my interpretation of the faulty regex:
%4d% - Get four digits.
[^\\n] - Look for those digits in between the beginning of the string and a new line.
Can anyone please correct my explanation and/or tell me why removing the slash gives me the result I expect?
I don't care for the HOW...I need the WHY.
Like #LucasTrzesniewski pointed out, that's sscanf() syntax, it has nothing to do with Regex. The format is explained in the sprintf() page.
In your pattern "%4d%[^\\n]", the two \\ translate to a single backslash character. So the correct interpretation of the "faulty" pattern is:
%4d - Get four digits.
%[^\\n] - Look for all characters that are not a backslash or the letter "n"
That's why it matches everything up until the "n" in "Jan" and "Jun".
The correct pattern is "%4d%[^\n]", where the \n translates to a new line character, and it's interpretation is:
%4d - Get four digits.
%[^\n] - Look for all characters that are not a new line

ERROR: preg_replace(): Delimiter must not be alphanumeric or backslash

I'am having trouble with a preg_replace() and I have tried to solve it for some time now.
I'am getting this error:
preg_replace: Delimiter must not be alphanumeric or backslash
Here is my code:
$id = 23;
$titleForUrl = "I_like_cookies";
$uploadShortDesc = "This is the best desc and I love it 1242";
$uploadShortDesc = preg_replace('\1242\',
'<a href="http:\/\/google.com\/freecookies\/'.$id.'-'.$titleForUrl.'">http:\/\/google.com\/freecookies\/'.$id.'-'.$titleForUrl.'.<\/a> ',
$uploadShortDesc);
echo $uploadShortDesc;
Is should echo:
This is the best desc and I love it http://google.com/freecookies/23-I_like_cookies.
I would love if someone could help me, I have put a \ in front of all / but I don't know why it won't work.
Thanks Fred -ii- for the help!
it should look like:
$uploadShortDesc = preg_replace('\1242\', 'http://google.com/freecookies/'.$id.'-'.$titleForUrl.'. ', $uploadShortDesc);
Thanks! I really should read that manual more...

Replace " ’ " with " ' " in PHP

I'm grabbing a string from the database that could be something like String’s Title however I need to replace the ’ with a ' so that I can pass the string to an external API. I've used just about every variation of escaped strings in str_replace() that I can think of to no avail.
$stdin = mb_str_replace('’', '\'', $stdin);
Implementation of mb_str_replace() here: http://www.php.net/manual/en/ref.mbstring.php#107631
I mean this:
<?php
function mb_str_replace($needle, $replacement, $haystack) {
return implode($replacement, mb_split($needle, $haystack));
}
echo mb_str_replace('’', "'", "String’s Title");
It may solve encoding problems.
I have just tested this:
echo str_replace('’', "'", $cardnametitle);
//Outputs: String's Title
Edit: I believe that entries in your database have been htmlentitiesed.
Note: I'm pretty sure this is not a good solution, even though it did solve your problem I think there should be a better way to do it.
Try this
$s = "String’s Title";
$h = str_replace("’","'",$s);
echo $h;
Also can Try with preg_replace
echo preg_replace('/\’/',"'","String’s Title");
I don't know why str_replace() is not working for you.
I feel you haven't tried it in correct way.
Refer LIVE DEMO
<?php
$str = "String’s Title";
echo str_replace('’', '\'', $str) . "\n";
echo str_replace("’", "'", $str);
?>
OUTPUT:
String's Title
String's Title
UPDATE 1:
You may need to try setting the header as
header('Content-Type: text/html; charset=utf-8');
I came across a similar issue trying to replace apostrophes with underscores... I ended up having to write this (and this was for a WordPress site):
$replace = array(",","'","’"," ","’","–");
$downloadTitle = str_replace( $replace,"_",get_the_title($gallery_id));
I'm new to PHP myself, and realize this is pretty hideous code, but it worked for me. I realized it was the "’" that REALLY needed to be factored in for some reason.

Separate quotes from string

The following code keeps giving me this error
Parse error: syntax error, unexpected T_VARIABLE in ...
?
$query_string = 'this is a test... "this is in quotes" mmm..chicken burgers... yummm...';
preg_match_all("/\".*\"|[^\s]*/", ­ $query_string, $matches);
echo "Matches:";
foreach($matches[0] as $token) {
echo $token . "<br />";
}
it is from this web page
Have you looked at the line referred to in the Error Message you noted?
Have you looked at the lines preceding that line, to ensure that you have ended each line with the semi-colon ";", that you have used the correct operators for joining variables ".", etc.?
This sounds like a simple PHP Syntax error.
I just ran the following code on my XAMPP server with no error messages apparent:
<?php
$query_string = 'this is a test... "this is in quotes" mmm..chicken burgers... yummm...';
preg_match_all("/\".*\"|[^\s]*/", $query_string, $matches);
echo "Matches:";
foreach($matches[0] as $token) {
echo $token . "<br />";
}
As Col. Shrapnel noted, you have hidden dash symbol (173 decimal, Hex 00ad) in your code right before $query_string. Remove that and you'll be much better.
Update: to be exact, you have [comma], [space], [space], [hidden dash], [space], '$query_string'.

Categories