Replace any string before "/", PHP - 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;
}

Related

Incremental strings in PHP

I want string format with incremental numbers. I've strings starting with alphabets and containing numbers with few leading 0's.
$string = M001; //input
$alf= trim(str_replace(range(0,9),'',$string)); //removes number from string
$number = preg_replace('/[A-Za-z]+/', '', $string);// removes alphabets from the string
$number+=1;
$custom_inv_id = $alf.$number;
Expected result:
input M002 output M003
input A00003 output A00004
Using above code if input is M002, I'm getting output as M3. How I can get M003? Number of 0's is not fixed.
Use PHP preg_match or str_replace and try this code :-
$str='M001';
preg_match('!\d+!', $str, $matches);
$num=(int)$matches[0];
$num++;
echo str_replace((int)$matches[0],'',$str);
echo $num;
Demo
<?php
$tests = ['M0', 'M1', 'M001', 'M9', 'M09', 'M010',
'M2M0', 'M2M1', 'M2M001', 'M2M9', 'M2M09', 'M2M010',
'M2M', 'MM', '9M'];
foreach ($tests as $string) {
if (preg_match('/([\w\W]+)([0-9]+)$/', $string, $matches)) {
$output_string = $matches[1] . ($matches[2] + 1);
echo '<p>' . $string . ' => ' . $output_string . '</p>';
} else {
echo '<p>' . $string . ' (nothing to increment)</p>';
}
}
$a = 'm002';
$pattern = '#(?P<word>[A-Za-z0]+)(?P<digtt>[1-9]+)#';
preg_match($pattern, $a, $matches);
$final = $matches['word'].(string)($matches['digtt']+1);
echo $final;
You can use the sprintf and preg_match functions to get your expected result.
First: Split your string with preg_match to seperated values to work with
Second: Format a new string with sprintf
http://php.net/manual/en/function.sprintf.php
http://php.net/manual/en/function.preg-match.php
function increase($string, $amount = 1) {
$valid = preg_match("#^(.)(0+)?(\d+)$#s", $string, $matches);
if($valid) {
list($match, $char, $zero, $integer) = $matches;
$integer += $amount;
return sprintf("%s%'.0" . (strlen($zero)+1) . "d", $char, $integer);
}
return null;
}
echo increase("M00001"); // M00002
echo increase("A001", 5); // A006
i hope this can help you . i have made some thing dynamic make M% also dynamic
<?php
$vl = "A00004";
$number = substr($vl ,1);
$num= substr_count($vl,0);
$num++;
$number++;
$string = "M%'. 0".$num."d";
echo sprintf($string, $number);
?>
i got this result
M00005
As leading 0 is copied, I would do it like this. It works if the leading chars is also lowercase. It's also a non-regex and non-array way.
$str = "M0099";
$num = ltrim($str, "a..zA..Z0");
$new = str_replace($num, $num + 1, $str);
Output:
echo $new; // string(6) "M00100"

PHP: remove word from sentence if it contains #

I want to remove words from sentence if word contains #, I am using php.
Input: Hi I am #RaghavSoni
Output: Hi I am
Thank You.
You could do:
$str = preg_replace('/#\w+/', '', $str);
This is not a good way, but it works :
<?php
$input="Hi I am #RaghavSoni";
$inputWords = explode(' ', $input);
foreach($inputWords as $el)
{
if($el[0]=="#" )
{
$input = str_replace($el, "", $input);
}
}
echo $input;
?>
while(strpos($string, '#') !== false) {
$location1 = strpos($string, "#");
$location2 = strpos($string, " ", $location1);
if($location2 !== false) {
$length = $location2 - $location1;
$string1 = substr($string, 0, $location1);
$string2 = substr($string, $location2);
$string = $string1 . $string2;
}
}
echo $string;
echo str_replace("#RaghavSoni", "", "Hi I am #RaghavSoni.");
# Output: Hi I am.

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

PHP and regex Task

I have a string in php formatted like this:
http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb
where aaa... and bbb.... represent random characters and are random in length.
I would like to parse the string so that I am left with this:
http://bbbbbbbbbbbbbbb
In this case I wouldn't recommend regex but a simple substring or explode
$data = "http://aaaaaaaaaa/*http://bbbbbbbbbbb"
$parts = explode('*', $data);
echo $parts[1];
fin :)
You don't need regular expressions at all in this case:
$str = 'http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb';
echo substr($str, strpos($str, 'http://', 1));
Hi This would help you to get the address:
$str = 'http://www.example.com/*http://www.another.org/';
$pattern = '/^http:\/\/[\.\w\-]+\/\*(http:\/\/.+)$/';
//$result = preg_replace($pattern, '$1', $str);
$found = preg_match_all($pattern, $str, $result);
$url = (!$found==0) ? $result[1][0] : '';
echo $str . '<br />' . $url;
Here is the regular expression way:
$str = 'http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb';
$url = preg_replace("/^.*(http:\/\/.*[^(http:\/\/)+])$/", "$1", $str);
echo $url;
Here is a clean solution: grab everything after the last occurrence of "http://".
$start = strrpos($input, 'http://');
$output = substr($input, $start);

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