Processing text in PHP finding a matching character - php

How can I process text with some codes.
So suppose I have text as below
Hello {::first_name::} {::last_name::},
How are you?
Your organisation is {::organisation::}
For any text between {:: and ::} should be evaluated to get its value.
I tried exploding text to array using space as delimiter and then parsing array items to look for "{::" and if found get string between "{::" and "::}" and calling database to get this field value.
So basically these will be db fields.
Below is the code I have tried
$msg = "Hello {::first_name::} {::last_name::},
How are you?
Your organisation is {::organisation::}";
$msg_array = explode(" ", $msg);
foreach ($msg_array as $str) {
if (strpos($str, "{::") !== false) {
$field_str = get_string_between($str, "{::", "::}");
$field_value = $bean->$field_str; //Logic that gets the value of the field
$msgStr .= $field_value . " ";
} else {
$msgStr .= $str . " ";
}
}
function get_string_between($string, $start, $end)
{
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}

Your script seems fine. Your script in fiddle
If you are looking for alternative way, you can try using preg_match_all() with str_replace(array, array, source)
<?php
$bean = new stdClass();
$bean->first_name = 'John';
$bean->last_name = 'Doe';
$bean->organisation = 'PHP Company';
$string = "Hello {::first_name::} {::last_name::}, How are you? Your organisation is {::organisation::}";
// find all placeholders
preg_match_all('/{::(.+?)::}/i', $string, $matches);
$placeholders = $matches[0];
//strings inside placeholders
$parts = $matches[1];
// return values from $bean by matching object property with strings inside placeholders
$replacements = array_map(function($value) use ($bean) {
// use trim() to remove unexpected space
return $bean->{trim($value)};
}, $parts);
echo $newstring = str_replace($placeholders, $replacements, $string);
Short format:
$string = "Hello {::first_name::} {::last_name::}, How are you? Your organisation is {::organisation::}";
preg_match_all('/{::(.+?)::}/i', $string, $matches);
$replacements = array_map(function($value) use ($bean) {
return $bean->{trim($value)};
}, $matches[1]);
echo str_replace($matches[0], $replacements, $string);
And if you prefer to use a function:
function holder_replace($string, $source = null) {
if (is_object($source)) {
preg_match_all('/{::(.+?)::}/i', $string, $matches);
$replacements = array_map(function($value) use ($source) {
return (property_exists(trim($value), 'source')) ? $source->{trim($value)} : $value;
}, $matches[1]);
return str_replace($matches[0], $replacements, $string);
}
return $string;
};
echo holder_replace($string, $bean);
OUTPUT:
Hello John Doe, How are you? Your organisation is PHP Company
fiddle

Or you can simply use str_replace function:
$data = "{:: string ::}";
echo str_replace("::}", "",str_replace("{::", "", $data));

Related

Deprecated each in code igniter xssclean helper

I have a codeigniter helper called xssclean for input validating form data
If i give array it show each deprecated error.
Here is my function in my xssclean_helper.php
function xssclean($str) {
if (is_array($str)) {
while (list($key) = each($str)) {
$str[$key] = $xssclean($str[$key]);
}
return $str;
}
$str = _remove_invisible_characters($str);
$str = preg_replace('|\&([a-z\_0-9]+)\=([a-z\_0-9]+)|i', _xss_hash() . "\\1=\\2", $str);
$str = preg_replace('#(&\#?[0-9a-z]{2,})([\x00-\x20])*;?#i', "\\1;\\2", $str);
$str = preg_replace('#(&\#x?)([0-9A-F]+);?#i', "\\1\\2;", $str);
$str = str_replace(_xss_hash(), '&', $str);
$str = rawurldecode($str);
$str = preg_replace_callback("/[a-z]+=([\'\"]).*?\\1/si", '_convert_attribute', $str);
$str = preg_replace_callback("/<\w+.*?(?=>|<|$)/si", '_html_entity_decode_callback', $str);
$str = _remove_invisible_characters($str);
$str = _remove_tabs($str);
$str = _never_allowed_str($str);
$str = _never_allowed_regx($str);
$str = str_replace(array('<?', '?' . '>'), array('<?', '?>'), $str);
$str = _never_allowed_words($str);
do {
$original = $str;
if (preg_match("/<a/i", $str)) {
$str = preg_replace_callback("#<a\s+([^>]*?)(>|$)#si", '_js_link_removal', $str);
}
if (preg_match("/<img/i", $str)) {
$str = preg_replace_callback("#<img\s+([^>]*?)(\s?/?>|$)#si", '_js_img_removal', $str);
}
if (preg_match("/script/i", $str) OR preg_match("/xss/i", $str)) {
$str = preg_replace("#<(/*)(script|xss)(.*?)\>#si", '', $str);
}
} while ($original != $str);
unset($original);
$event_handlers = array('[^a-z_\-]on\w*', 'xmlns');
$str = preg_replace("#<([^><]+?)(" . implode('|', $event_handlers) . ")(\s*=\s*[^><]*)([><]*)#i", "<\\1\\4", $str);
$naughty = 'alert|applet|audio|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|isindex|layer|link|meta|object|plaintext|style|script|textarea|title|video|xml|xss';
$str = preg_replace_callback('#<(/*\s*)(' . $naughty . ')([^><]*)([><]*)#is', '_sanitize_naughty_html', $str);
$str = preg_replace('#(alert|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2(\\3)", $str);
$str = _never_allowed_str($str);
$str = _never_allowed_regx($str);
return $str;
}
At line no 3 i get error
The each() function is deprecated with PHP 7.2. But you can replace your while-loop with a foreach-loop:
function xssclean($str) {
if (is_array($str)) {
foreach($str as &$value){
$value = xssclean($value);
}
return $str;
}
// …
}
The $value variable is per default a copy of the array value. The & makes it a reference, this way you can update the value.
Manipulating the array while iterating over it, is not a good idea and can lead to errors.

PHP How to Replace string with empty space? [duplicate]

This question already has answers here:
PHP: Best way to extract text within parenthesis?
(8 answers)
Closed last year.
Input:
GUJARAT (24)
Expected Output:
24
String Format:
State Name (State Code)
How can I remove State Code with parentheses?
You can also use php explode:
$state = "GUJARAT (24)";
$output = explode( "(", $state );
echo trim( $output[0] ); // GUJARAT
$str = "GUJARAT (24)";
echo '<br />1.';
print_r(sscanf($str, "%s (%d)"));
echo '<br />2.';
print_r(preg_split('/[\(]+/', rtrim($str, ')')));
echo '<br />3.';
echo substr($str, strpos($str, '(')+1, strpos($str, ')')-strpos($str, '(')-1);
echo '<br />4.';
echo strrev(strstr(strrev(strstr($str, ')', true)), '(', true));
echo '<br />5.';
echo preg_replace('/(\w+)\s+\((\d+)\)/', "$2", $str);
If you know the stateCode length, and it is fixed
$state = "GUJARAT (24)";
$state = substr($state, strpos($state, "(") + 1, 2);
// get string upto "(", and remove right white space
echo $state;
You can check more about substr and strpos in php manual.
If stateCode length is not fixed, you can use regular expression:-
$state = 'GUJARAT (124)';
preg_match('/(\d+)/', $state, $res);
$stateCode = $res[0];
var_dump($stateCode);
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');
echo $parsed; // (result = dog)
you can use the function preg_match
$state = 'GUJARAT (24)'
$result = [];
preg_match('/[\(][\d]+[\)]/', $state, $result);
$stateCode = $result[0] // (24)
$stateCode = substr($stateCode, 1, strlen($stateCode) - 2); // will output 24

Replacing text between two limts

I have been trying to get the text between two symbols to be replaced with preg_replace, but alas still not quite getting it right as I get a null output that is empty string, this is what I have so far
$start = '["';
$end = '"]';
$msg = preg_replace('#('.$start.')(.*)('.$end.')#si', '$1 test $3', $row['body']);
So an example output I am looking for would be:
normal text [everythingheregone] after text
To
normal text [test] after text
You are defining $start and $end as arrays, but using it as normal variables. Try changing your code to this:
$start = '\[';
$end = '\]';
$msg = preg_replace('#('.$start.')(.*)('.$end.')#si', '$1 test $3', $row['body']);
How about
$str = "normal text [everythingheregone] after text";
$repl = "test";
$patt = "/\[([^\]]+)\]/";
$res = preg_replace($patt, "[". $repl ."]", $str);
Should yield normal text [test] after text
EDIT
Fiddle demo here
some functions that may help
function getBetweenStr($string, $start, $end)
{
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
and
function getAllBetweenStr($string, $start, $end)
{
preg_match_all( '/' . preg_quote( $start, '/') . '(.*?)' . preg_quote( $end, '/') . '/', $string, $matches);
return $matches[1];
}
$row['body']= "normal text [everythingheregone] after text ";
$start = '\[';
$end = '\]';
$msg = preg_replace('#'.$start.'.*?'.$end.'#s', '$1 [test] $3', $row['body']);
//output: normal text [test] after text done
I have a regex approach. The regular expression is :\[.*?]
<?php
$string = 'normal text [everythingheregone] after text ';
$pattern = '\[.*?]';
$replacement = '[test]'
echo preg_replace($pattern, $replacement, $string);
//normal text [test] after text
?>

Replace name element using regex

I am trying to replace this "iwdnowfreedom[body_style][var]" with this "iwdnowfreedom_body_style_var" in the name attributes of a variable. There could be several array keys but for my situation stripping them out shouldn't result in any issues.
Here is the code I have so far:
$pattern = '/name\\s*=\\s*["\'](.*?)["\']/i';
$replacement = 'name="$2"';
$fixedOutput = preg_replace($pattern, $replacement, $input);
return $fixedOutput;
How can I fix this to work properly?
You could try using the build in str_replace function to achieve what you are looking for (assuming there are no nested bracked like "test[test[key]]"):
$str = "iwdnowfreedom[body_style][var]";
echo trim( str_replace(array("][", "[", "]"), "_", $str), "_" );
or if you prefer regex (nested brackets work fine with this method):
$input = "iwdnowfreedom[body_style][var]";
$pattern = '/(\[+\]+|\]+\[+|\[+|\]+)/i';
$replacement = '_';
$fixedOutput = trim( preg_replace($pattern, $replacement, $input), "_" );
echo $fixedOutput;
I think you also meant that you might have a string such as
<input id="blah" name="test[hello]" />
and to parse the name attribute you could just do:
function parseNameAttribute($str)
{
$pos = strpos($str, 'name="');
if ($pos !== false)
{
$pos += 6; // move 6 characters forward to remove the 'name="' part
$endPos = strpos($str, '"', $pos); // find the next quote after the name="
if ($endPos !== false)
{
$name = substr($str, $pos, $endPos - $pos); // cut between name=" and the following "
return trim(preg_replace('/(\[+\]+|\]+\[+|\[+|\]+)/i', '_', $name), '_');
}
}
return "";
}
OR
function parseNameAttribute($str)
{
if (preg_match('/name="(.+?)"/', $str, $matches))
{
return trim(preg_replace('/(\[+\]+|\]+\[+|\[+|\]+)/i', '_', $matches[1]), '_');
}
return "";
}

Simple: How to replace "all between" with php? [duplicate]

This question already has answers here:
How to remove text between tags in php?
(6 answers)
Closed 3 years ago.
$string = "<tag>i dont know what is here</tag>"
$string = str_replace("???", "<tag></tag>", $string);
echo $string; // <tag></tag>
So what code am i looking for?
A generic function:
function replace_between($str, $needle_start, $needle_end, $replacement) {
$pos = strpos($str, $needle_start);
$start = $pos === false ? 0 : $pos + strlen($needle_start);
$pos = strpos($str, $needle_end, $start);
$end = $pos === false ? strlen($str) : $pos;
return substr_replace($str, $replacement, $start, $end - $start);
}
DEMO
$search = "/[^<tag>](.*)[^<\/tag>]/";
$replace = "your new inner text";
$string = "<tag>i dont know what is here</tag>";
echo preg_replace($search,$replace,$string);
outputs:
<tag>your new inner text</tag>
$string = "<tag>I do not know what is here</tag>";
$new_text = 'I know now';
echo preg_replace('#(<tag.*?>).*?(</tag>)#', '$1'.$new_text.'$2' , $string); //<tag>I know now</tag>
A generic and non-regex solution:
I've modified #felix-kling's answer. Now it only replaces text if it finds the needles.
Also, I've added parameters for replacing the needles, starting position and replacing all the matches.
I've used the mb_ functions for making the function multi-byte safe.
If you need a case insensitive solution then replace mb_strpos calls with mb_stripos.
function replaceBetween($string, $needleStart, $needleEnd, $replacement,
$replaceNeedles = false, $startPos = 0, $replaceAll = false) {
$posStart = mb_strpos($string, $needleStart, $startPos);
if ($posStart === false) {
return $string;
}
$start = $posStart + ($replaceNeedles ? 0 : mb_strlen($needleStart));
$posEnd = mb_strpos($string, $needleEnd, $start);
if ($posEnd === false) {
return $string;
}
$length = $posEnd - $start + ($replaceNeedles ? mb_strlen($needleEnd) : 0);
$result = substr_replace($string, $replacement, $start, $length);
if ($replaceAll) {
$nextStartPos = $start + mb_strlen($replacement) + mb_strlen($needleEnd);
if ($nextStartPos >= mb_strlen($string)) {
return $result;
}
return replaceBetween($result, $needleStart, $needleEnd, $replacement, $replaceNeedles, $nextStartPos, true);
}
return $result;
}
$string = "{ Some} how it {is} here{";
echo replaceBetween($string, '{', '}', '(hey)', true, 0, true); // (hey) how it (hey) here{
If "tag" changes:
$string = "<tag>i dont know what is here</tag>";
$string = preg_replace('|^<([a-z]*).*|', '<$1></$1>', $string)
echo $string; // <tag></tag>
If you don't know what's inside the <tag> tag, it's possible there is another <tag> tag in there e.g.
<tag>something<tag>something else</tag></tag>
And so a generic string replace function won't do the job.
A more robust solution is to treat the string as XML and manipulate it with DOMDocument. Admittedly this only works if the string is valid as XML, but I still think it's a better solution than a string replace.
$string = "<tag>i don't know what is here</tag>";
$replacement = "replacement";
$doc = new DOMDocument();
$doc->loadXML($str1);
$node = $doc->getElementsByTagName('tag')->item(0);
$newNode = $doc->createElement("tag", $replacement);
$node->parentNode->replaceChild($newNode, $node);
echo $str1 = $doc->saveHTML($node); //output: <tag>replacement</tag>
$string = "<tag>i dont know what is here</tag>"
$string = "<tag></tag>";
echo $string; // <tag></tag>
or just?
$string = str_replace($string, "<tag></tag>", $string);
Sorry, could not resist. Maybe you update your question with a few more details. ;)
If you need to replace the portion too then this function is helpful:
$var = "Nate";
$body = "Hey there {firstName} have you already completed your purchase?";
$newBody = replaceVariable($body,"{","}",$var);
echo $newBody;
function replaceVariable($body,$needleStart,$needleEnd,$replacement){
while(strpos($body,$needleStart){
$start = strpos($body,$needleStart);
$end = strpos($body,$needleEnd);
$body = substr_replace($body,$replacement,$start,$end-$start+1);
}
return $body;
}
I had to replace a variable put into a textarea that was submitted. So I replaced firstName with Nate (including the curly braces).

Categories