PHP + Modify string - php

I have got a string and would like to remove everything after a certain "dot"+word combination. For instance:
This.Is.A.Test
=> would become
This.Is.A

Were you looking to remove everything after a specific dot+word, or just remove the last dot+word? If you're looking for a specific word, try this:
$str = "This.Is.A.Test";
$find = ".A";
$index = strpos($str, $find);
if ($index !== false)
$str = substr($str, 0, $index + strlen($find));
echo $str; // "This.Is.A"
In response to #SuperSkunk:
If you wanted to match the whole word, you could do this:
$find = ".A.";
$str = "This.Is.A.Test";
$index = strpos($str, $find);
if ($index !== false)
$str = substr($str, 0, $index + strlen($find) - 1);
echo $str; // "This.Is.A"
$str = "This.Is.AB.Test";
$index = strpos($str, $find);
if ($index !== false)
$str = substr($str, 0, $index + strlen($find) - 1);
echo $str; // "This.Is.AB.Test" (did not match)

$str = "This.Is.A.Test"; $str = substr($str, 0, strrpos($str, "."));

$result = explode('.', $str, 4);
array_pop($result);
implode('.', $result);

I'll do something very simple like :
<?php
$string = 'This.Is.A.Test';
$parts = explode('.', $string);
array_pop($parts); // remove last part
$string = implode('.', $parts);
echo $string;
?>

$pos = strpos($haystack, ".A" );
$result = substr($haystack,0,$pos);
...something like this.

Related

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.

How to remove specific html tags from a line in string?

$find = '{<p>something</p>}';
$str1 = "<p>{<p>something</p>}</p>\r\ntext<p>something else</p>";
// or
$str2 = "<p>something</p>\r\n{<p>something</p>}aa<p>t</p>\r\ntext<p>something else</p>";
Basically, $find can be anywhere in the string. New lines delimiter is "\r\n".
I need to find $find in the $str and remove specific html tags around $find in that specific string line. No tags should be removed from $find.
Expected output would be
// For $str1
$str1 = "{<p>something</p>}\r\ntext<p>something else</p>";
// For $str2
$str2 = "<p>something</p>\r\n{<p>something</p>}aat\r\ntext<p>something else</p>";
The string might be very long, so no regex solutions please.
What I have figured out:
$pos = strpos($str, $find);
if ($pos !== false) {
$contentLength = strlen($str);
$lineStart = (int)strrpos($str, "\r\n", -$contentLength+$pos); // cast false to 0 (start of string)
$lineEnd = strpos($str, "\r\n", $pos);
if ($lineEnd === false)
$lineEnd = strlen($str);
$lineLength = $lineEnd-$lineStart;
if ($lineLength < 0)
return;
var_dump(substr($str, $lineStart, $lineLength));
}
Which dumps that specific line in the string.
My final solution:
function replace($find, $str, $replace) {
$pos = strpos($str, $find);
if ($pos !== false) {
$delim = "\r\n";
$contentLength = strlen($str);
$lineStart = strrpos($str, $delim, -$contentLength+$pos);
if ($lineStart === false)
$lineStart = 0;
else
$lineStart += strlen($delim);
$lineEnd = strpos($str, $delim, $pos);
if ($lineEnd === false)
$lineEnd = strlen($str);
$lineLength = $lineEnd - $lineStart;
$line = substr($str, $lineStart, $lineLength);
$posLine = strpos($line, $find); // Where $find starts
$findLength = strlen($find);
$line = substr_replace($line, '', $posLine, $findLength); // Remove $find from $line
$begin = replaceTags(substr($line, 0, $posLine));
$end = replaceTags(substr($line, $posLine));
return substr_replace($str, $begin.$replace.$end, $lineStart, $lineLength);
}
}
function replaceTags($str) {
return str_replace(array('<p>', '</p>'), '', $str);
}
echo replace($find, $str, $replace);

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

How to find position of a character in a string in PHP

How to find positions of a character in a string or sentence in php
$char = 'i';
$string = 'elvis williams';
$result = '3rd ,7th and 10th'.
I tried strpos..but no use..
This will give you the position of $char in $string:
$pos = strpos($string, $char);
If you want the position of all occurences of $char in string:
$positions = array();
$pos = -1;
while (($pos = strpos($string, $char, $pos+1)) !== false) {
$positions[] = $pos;
}
$result = implode(', ', $positions);
print_r($result);
Test it here: http://codepad.viper-7.com/yssEK3

Replace multiple occurrences of same symbol using preg_replace?

Let's say I have a string like this:
$string = "hello---world";
How would I go about replacing the --- with a single hyphen?
The string could easily look like this instead:
$string = "hello--world----what-up";
The desired result should be:
$string = "hello-world-what-up";
$string = preg_replace('/-{2,}/','-',$string);
To remove them from the beginning and the end:
$string = trim($string, '-');
try $string = preg_replace('/-+/', '-', $string)
$string = preg_replace('/--+/', '-', $string);
Here's the function I'm using - works like a charm :)
public static function setString($phrase, $length = null) {
$result = strtolower($phrase);
$result = trim(preg_replace("/[^0-9a-zA-Z-]/", "-", $result));
$result = preg_replace("/--+/", "-", $result);
$result = !empty($length) ? substr($result, 0, $length) : $result;
// remove hyphen from the beginning (if exists)
$first_char = substr($result, 0, 1);
$result = $first_char == "-" ? substr($result, 1) : $result;
// remove hyphen from the end (if exists)
$last_char = substr($result, -1);
$result = $last_char == "-" ? substr($result, 0, -1) : $result;
return $result;
}

Categories