Evaluate a string as PHP code without using eval [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Seeing how eval should be avoided, how do you evaluate a string as PHP code without using eval? For example consider this code:
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
$str = "\"$str\""; // Now I have a string with double quotes around it.
// how to get the contents of $str evaluated without using eval()
?>
I can get the desired result by using eval like so - eval("echo $str;");, but eval is exactly what I am looking to avoid.
You might view this as a question of removing the double quotes. But it isn't about that. As #AmalMurali points out, what I am asking here is how to get the contents of $str evaluated without using eval()

You can layout your code like this:
$string = 'cup';
$name = 'coffee';
$str = 'This is a ' . $string . ' with my ' . $name . ' in it.';
Or perhaps like this, using sprintf which is my personal favorite method of handling cases like this:
$string = 'cup';
$name = 'coffee';
$str = sprintf('This is a %s with my %s in it.', $string, $name);
There are different options based on personal style & preference.

What you really want here is to use double quotes for $str so that variable replacement can take place.
See also the docs: http://www.php.net/manual/it/language.types.string.php#language.types.string.syntax.double

Why are you adding double quotes then removing them? For a simple string variable inclusion you just use double quotes like
$string = 'cup';
$name = 'coffee';
$str = "This is a $string with my $name in it.";
echo $str;

Related

How to exchange numbers in string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
can you please help me with finding right function for exchanging numbers in string? Numbers are separated with ":".
For example
"2:0" to "0:2"
"101:50" to "50:101"
Thank you.
There are many ways to do it, you can try the any of the ways here.
<?php
//using regex
$re = '/(\d+):(\d+)/i';
$str = '50:101';
$subst = '$2:$1';
$result = preg_replace($re, $subst, $str);
echo "The string $str after exchange is ".$result;
echo PHP_EOL;
// concatenating parts after explode
$parts = explode(':',$str);
echo "The string $str after exchange is $parts[1]:$parts[0]";
echo PHP_EOL;
//using explode, array_reverse and implode
$str = '50:101';
$result = implode(':', array_reverse(explode(':',$str)));
echo "The string $str after exchange is ".$result;
?>
DEMO: https://3v4l.org/OkY18
Simply explode() the string and then reform it.
$str = '100:200';
$bits = explode(':',$str);
echo $bits[1] . ':' . $bits[0];
RESULT
200:100

How to replace spacial character (') to space in php string [duplicate]

This question already has answers here:
How do I replace certain parts of my string?
(5 answers)
Closed 6 years ago.
I want to replace special character single quotes(') with space . In Java it is easy but i dont know how to do this in php.
<?php $data = str_replace("'", " ", string);
echo $data;
?>
to remove just single quote :
$FileName = str_replace("'", " ", string);
to remove other characters as well, use array :
$remove[] = "'";
$remove[] = '"';
$remove[] = "-"; // just as another example
$FileName = str_replace( $remove, " ", string);
You can use str_replace() string function in php.
Example : echo str_replace(" ' "," ","India' ");
Explanation : Here, in str_replace() function first argument you need to pass string which you want to replace. For second argument you need to pass string you want to replace with existing. And for third and last argument you need to pass your original string in which you need replace.

PHP explode string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have this string: 0|DY1497ORYOSLDY932OSLCPH|1|0|0
and I need to explode it like that:
0| DY1497 ORY OSL DY932 OSL CPH |1|0|0
$string1 = 'DY1497';
$string2 = 'ORY';
$string3 = 'OSL';
$string4 = 'DY932';
$string5 = 'OSL';
$string6 = 'CPH';
I searched, but all I could find is how to explode when the text is separated with /, -, etc. Any ideas?
The best choice is probably a regex:
if (preg_match('/|(.{6})(.{3})(.{3})(.{5})(.{3})(.{3})|/', $string, $matches)) {
echo $matches[1];
echo $matches[2];
echo $matches[3];
echo $matches[4];
echo $matches[5];
echo $matches[6];
}
This divides the string simply by length in characters. You may need to modify this as needed. See http://regular-expressions.info
I suggest to use substr() if you know the exact position of the characters you need
Son, it looks to me like you searching for some specific tokens up in this here string. What I reckon you can do is, make yerself one array outa little search patterns you might be a looking fer. Something like this here:
$patterns = array('ORY', 'OSL', 'CPH', 'DY[\d]+');
Then you can make yerself a nice big regexp outa that:
$regexp = '/(' . implode('|', $patterns) . ')/';
Then, what you gonna do is, use preg_match_all to find every one of them fellers thisaway:
preg_match_all($regexp, $string, $matches);
Now, you do that and then looka what you got in $matches. I'd wager it has what you need.
Another way of splitting up strings that consists of fixed length fields is with 'unpack' which is very suited to this job.
here is some tested code that demonstrates it:
<?php
$origSource = '0|DY1497ORYOSLDY932OSLCPH|1|0|0';
// expected result
$string1 = 'DY1497';
$string2 = 'ORY';
$string3 = 'OSL';
$string4 = 'DY932';
$string5 = 'OSL';
$string6 = 'CPH';
// get the string we are interested in...
$tempStr = explode('|', $origSource);
$source = $tempStr[1]; // string with fixed length fields
/* debug */ var_dump($source);
// define where the fixed length fields are and the indexes to call them in the output array
$format = 'A6field1/' . 'A3field2/' . 'A3field3/'. 'A5field4/'. 'A3field5/'. 'A*field6/' ; // make it clear where the fields are...
$dest = unpack($format, $source);
/* debug */ var_dump($dest);
?>
firstly you have to concat your string with a special character like -,#,$ etc...
then you can explode it.
after that you may use the following syntax in php to explod string......
<?php
$string= "0|$DY1497$ORY$OSL$DY932$OSL$CPH$|1|0|0";
$pieces = explode("$", $string);
?>
For see your Result:---
<?php
foreach ($pieces as $value)
{
echo "piece: $value<br />";
}
?>
I hope it will help you.

Reverse Order of String like "Hello Word" reverse as "Word Hello" in PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i need to reverse String "Hello Word" into "Word Hello", it could be "My Name is Khan" reverse into "Khan is Name My" in PHP
$str = "My Name is Khan";
$reverse = implode(" ",array_reverse(explode(" ", $str)));
echo $reverse;
Result is Khan is Name My.
explode splits the string into an array in accordance to the delimiter, which in this case is " ". array_reverse is self-explanatory, it reverses the order of the array. implode then joins the string using the delimiter.
You might think to code something to show then let us help you with the answer, but let me describe the logic, since you are going to input it as a string, you might think to split the character based on the character you wanted to split
you might consider this EXPLODE
After you finish and put that split into an array. You can reverse it back using looping or perhaps you want to reverse using THIS
$string = "My Name is Khan";
$new = explode(' ', $string);
$new = array_reverse($new);
print_r(implode(' ', $new));
At first, requirement is: reverse the order of words not alphabets.
So, need to split the string by spaces(as words are separated by spaces).
This way, an array is generated like:
array('World', 'Hello');
Change the sequence of array using array_reverse()
The resulting array would be:
array('Hello', 'World');
Now, again join the above array by space:
The resulting string would be:
Hello World
Try this:
<?php
$name = 'World Hello';
$temp = explode(' ', $name);
echo '<pre>';
print_r($temp);
echo '</pre>';
$arr = array_reverse($temp);
echo '<pre>';
print_r($arr);
echo '</pre>';
$str = implode(' ', $arr);
echo $str;
?>

Using PHP how do I test a string for a pattern then alter it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In PHP given this string:
$string = '/sometext?123#abc/moretext';
How can I test for the existence of the pattern "?123#abc/" which will always be enclosed by "?" and "/" but have varying inner-text that may include any text and symbols? The text outside of the pattern will also be different. I need to do this:
if ($string includes pattern ?*/) {
//load the inner value into a variable
//then remove the entire patern including the leading "?" and trailing "/" and replace with a single "/"
}
How do I do this?
<?php
$string = '/sometext?123#abc/moretext';
$pattern = '/\\?(.*?)\\//';
if( $pieces = preg_split($pattern, $string, Null, PREG_SPLIT_DELIM_CAPTURE)) {
echo($pieces[1] . "\n");
unset($pieces[1]);
echo(implode("/", $pieces) . "\n");
}
?>
--output:--
~/php_programs$ php 1.php
123#abc
/sometext/moretext
Try this
$s = '/sometext?123#abc/moretext';
$matches = array();
$t = preg_match('#\?(.*?)\/#s', $s, $matches);
if($matches[1])
echo "match";
else
echo "not";
Output
match
Codepad

Categories