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

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).

Related

Processing text in PHP finding a matching character

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));

Check if substring is contained anywhere in the actual string

I have the following string:
$str = "A string".
When I use:
preg_match("/A string/", $str)
I get the match everything works perfectly fine, but I want to use the same regular expression for another string:
$str2 = "A test string".
For this case I can use:
"/A (test )?string/"
But I want it to be more complex, it should also be able to match strings like this, for example:
A sttest ring
test A string
I mean that the substring "test " can appear anywhere in the subject.
Is it even possible to find a regular expression for this?
You could try something like this
$str = "My test String";
if (strpos($str, 'test') !== false) {
echo 'true';
}
Try this:
$str = "A sttest ring";
$newstr = preg_replace("/\s*test\s*/", "", $str);
preg_match("/A string/", $newstr, $matches);
echo $matches ? 'true' : 'false';
Online Demo
I would create a function for that:
function containsLetters($testString, $lettersString, $caseSensitive = false, $whiteSpaces = false){
if(!$caseSensitive){
$testString = strtolower($testString); $lettersString = strtolower($lettersString);
}
if($whiteSpaces){
$tw = $testString; $lw = $lettersString;
}
else{
$tw = preg_replace('/\s/', '', $testString); $lw = preg_replace('/\s/', '', $lettersString);
}
$tst = str_split($tw); $ltr = str_split($lw); $c = count($ltr); $r = array();
foreach($ltr as $l){
foreach($tst as $i => $t){
if($l === $t){
$a = array_splice($tst, $i, 1); $r[] = $a[0];
}
}
}
if(count($r) >= $c){
return true;
}
return false;
}
$test = containsLetters('A sttest ring', 'a test string');
Just pass true to the 3rd argument to make it case sensitive. Also, pass true to the 4th argument to compare white spaces.

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 "";
}

Replace any string before "/", PHP

I want to replace any string before "/", irrespective of the string length.
Thanks
Jean
one way, assuming you want to change the string before the first "/".
$str = "anystring/the_rest/blah";
$s = explode("/",$str);
$s[0]="new string";
print_r ( implode("/",$s) );
echo preg_replace('/^[^\/]+/', 'baz', 'foo/bar');
Something like that would be the most efficient, although i still prefer the preg_replace() technique
$pos = strpos($input, '/');
if ($pos >= 0) {
$output = $replacement . substr($input, $pos);
} else {
$output = $input;
}

Categories