Substitute a variable in PHP expression with its value - php

It is simple thing but I cannot resolve it myself.
I am trying to extract part of a string using substr:
$Text=substr($FullText, 0, 6);
Where $FullText is a varaible containing a string.
I guess substr does not like variable and needs a string in quotas.
My question is how can I substitute variable in PHP expression with its value?
Thank you very much in advance!

$text=substr($fulltext, 0, 6);
it will work, Substr function receives string in double quotes or you can put php variable in it. Try to echo this, it will work as required

You posted this code fragment in a comment to the question:
$FullText=$ExchangePart->Item(5)->nodeValue;
//actual value of the variable is: "1.6598 6.479460 5.4545"
$Text=substr($FullText, 0, 6);
//$Text=$ExchangePart->Item(5)->nodeValue;
echo $Text;
It looks like you are handling XML here. The SimpleXMLElement class (the type of the objects created by the simplexml_*() functions) is a beast with many faces. If you try to:
echo($ExchangePart->Item(5)->nodeValue);
or
print_r($ExchangePart->Item(5)->nodeValue);
it is presented as a string but, in fact, it is also an SimpleXMLElement object.
The solution to the issue is very simple: you have to explicitly convert the value you want to a string:
$FullText = (string)$ExchangePart->Item(5)->nodeValue;
Now the value of $FullText is a string; you can safely pass it to any string processing function and it will work as described in the documentation.

Related

PHP - str_replace

I'm having some trouble using str_replace, this block below
|0460|001|CREDITO SIMPLES NACIONAL|
when I use this:
str_replace("|0460|001|CREDITO SIMPLES NACIONAL|","a", $registroC100, $replaces);
the var $replaces increase, but the text keep the same, I'm doing something wrong?
Edit:
this is how is in my code
$registroC100 = str_replace("|0460|001|CREDITO SIMPLES NACIONAL|","a",$registroC100);
str_replace not changes your variable value unless you do it using the return value of str_replace function.
Take a look at the documentation right here https://www.php.net/manual/pt_BR/function.str-replace.php
<?php
$replaces = 0;
$registroC100 = '|0460|001|CREDITO SIMPLES NACIONAL|';
$registroC100 = str_replace("|0460|001|CREDITO SIMPLES NACIONAL|","a", $registroC100, $replaces);
From your php syntax the str_replace structure and required parameters are okay.
str_replace("|0460|001|CREDITO SIMPLES NACIONAL|","a", $replaces);
It means search the string stored in variable $registroC100, find the value "|0460|001|CREDITO SIMPLES NACIONAL|", replace it with "a" and count the number of replacement in variable $replace. The problem could be from the value of the string you are searching. What is the value of the variable $registroC100. Show us the variable declaration and initialization.

PHP - get_file_contents not working as an array?

I'm using a $file_contents = file_get_contents($file_name) then using $file_contents = array_splice($file_contents, 30, 7, 'changedText') to update something in the file code. However, this keeps resulting in:
Warning: array_splice(): The first argument should be an array
From what I understand the string returned by file_get_contents() should be able to be acted on like any other array. Any reason I'm having trouble with this? Thank you much!
From the manual:
file_get_contents — Reads entire file into a string
So you don't have an array. You have a string.
Read documentation.
String is not an array even when it supports using square brackets:
$str[0]
Use str_split function for behavior you want. It will convert your string into real array, and then you can use it as an argument in array_splice function. E.g:
echo('<pre>');
var_dump(array_slice(str_split("Stack Overflow"), 6));
echo('</pre>');
die();
I think it helps.

PHP http_build_query special symbols

I want to create an url out of an array with the help of http_build_query (PHP). This is the Array:
$a = array("skip" => 1, "limit" => 1, "startkey" => '["naturalProduct","Apple"]')
After calling
$s = http_build_query($a);
I get the following string $s:
skip=1&limit=1&startkey=%5B%22naturalProduct%22%2C%22Apple%22%5D
My problem is, that I would need an url like this:
skip=1&limit=1&startkey=["naturalProduct","Apple"]
which means, that I don't want to convert the following symbols: ",[]
I have written a conversion function which I call after the http_build_query:
str_replace(array("%5B", "%22", "%5D", "%2C"), array('[', '"', ']', ','), $uri);
My question now: Is there a better way to reach the expected results?
My question now: Is there a better way to reach the expected results?
Yes, there is something better. http_build_query­Docs by default uses an URL encoding as outlined in RFC 1738. You just want to de-urlencode the string. For that there is a function that does this in your case: urldecode­Docs:
$s = http_build_query($a);
echo urldecode($s);
I hope you are aware that your URL then is no longer a valid URL after you've done that. You already decoded it.
You don't need to decode the special characters - they are automatically decoded when PHP's $_GET superglobal is generated. When I do print_r($_GET) with your generated string, I get this:
Array ( [skip] => 1 [limit] => 1 [startkey] => [\"naturalProduct\",\"Apple\"] )
Which has decoded every character, but hasn't unescaped the double quotes. To unescape them, use stripslashes():
echo stripslashes($_GET['startkey']);
This gives
["naturalProduct","Apple"]
Which you can then parse or use however you wish. A better solution, as ThiefMaster mentions in the comments, is to disabled magic_quotes_gpc in your php.ini; it's deprecated and scheduled for removal completely in PHP6.

How to choose between explode and regex

My string is to contain some "hotkeys" of the form [hotkey]. For example:
"This is a sample string [red] [h1]"
When I process this string with a php function, I'd like function to output the original string as follows;
<font color='red'><h1>This is a sample string</h1></font>
I'd like to use this function purely for convenience purposes easing some typing. I may use a font tag or div or whatever, let's not get into that. The point is this; a hotkey will cause the original string to be wrapped into
<something here>original string<and something there>
So the function first needs to determine if there are any hotkeys or not. That's easy; just check to see if there is any existence of [
Then we will need to process the string to determine which hotkeys exist and get into the biz logic as to which wrappers to be deployed.
and finally we will have to clean the original string from the hotkeys and return the results back.
My question is if there is a regex that would make this happen more effectively then the following parsing method that I am planning of implementing the function as.
step 1
explode the string into an array using the [ delimiter
step 2
go thru each array element to see if the closing ] is present and it forms one of the defined hotkeys, and if so, do the necessary.
Obviously, this method is not using any regex power. I'm wondering if regex could be of help here. Or, any better way to do it you may suggest?
If [ and ] are the only delimeters you need to worry about, you could probably use strtok
I don't speak english well but I saw your example :
"This is a sample string [red] [h1]"
<font color='red'><h1>This is a sample string</h1></font>
If I were you :
$red = substr( $chaine, strpos($chaine, '['), strpos($chaine, ']') );

PHP : How to get the current value of an array being traversed within an inbuilt function like strpos?

eg. I want to replace instances of some words with their string length
"XXXX is greater than XX" becomes "4 is greater than 2"
Code that I intend to write :
$myStrings = Array("XX","XXX","XXXX","XXXXX");
$outStr = str_replace($myStrings,strlen(current($myStrings)),$outStr);
But here CURRENT is not working.
P.S. Please do not suggest workarounds to do this stuff since that is not what I intend to ask the forum. My query is getting current pointer to an array being traversed internally.
Thank You.
The function you are looking for is array_map. It applies a function to all elements of an array and outputs the results as a new array:
$myStrings = Array("XX","XXX","XXXX","XXXXX");
$outStr = str_replace($myStrings,array_map('strlen', $myStrings)),$outStr);
This might create a new problem as XXXX will be replaced with 22 before XXXX is checked. The solution to this would be reverse the input array:
$myStrings = array_reverse(Array("XX","XXX","XXXX","XXXXX"));
$outStr = str_replace($myStrings,array_map('strlen', $myStrings)),$outStr);
I don't think you can. Since it's an internal implementation, what would PHP expose to you that you could use to determine the current element?
Note that this is different from accessing internal array pointers using current(), key(), next(), reset() et al. I'm referring to the fact that PHP has an internal implementation of str_replace() for handling replacements of arrays of strings.
A quick test reveals that PHP doesn't even seem to bother with array pointers when replacing them with str_replace() anyway:
$arr = array('a', 'b', 'c'); // Internal pointer is at a
$str = 'abc';
next($arr); // Internal pointer is at b
echo str_replace($arr, 'x', $str), "\n"; // xxx
echo current($arr), "\n"; // b
Oh, by the way, this is what the manual for str_replace() says (strong emphasis mine):
If search is an array and replace is a string, then this replacement string is used for every value of search.
So specifically for str_replace(), I don't think it was ever intended for you to pass in a replacement string that is dynamic based on the input array.
And http://www.php.net/manual/de/function.array-walk.php isn´t an option?

Categories