PHP Function to Delete All Between Certain Character(S) in String

PHP function to delete all between certain character(s) in string

<?php

$string = 'Some valid and <script>some invalid</script> text!';
$out = delete_all_between('<script>', '</script>', $string);
print($out);

function delete_all_between($beginning, $end, $string) {
$beginningPos = strpos($string, $beginning);
$endPos = strpos($string, $end);
if ($beginningPos === false || $endPos === false) {
return $string;
}

$textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);

return delete_all_between($beginning, $end, str_replace($textToDelete, '', $string)); // recursion to ensure all occurrences are replaced
}

Remove portion of a string after a certain character

$variable = substr($variable, 0, strpos($variable, "By"));

In plain english: Give me the part of the string starting at the beginning and ending at the position where you first encounter the deliminator.

Removing all characters before certain string

There is a php built in for doing this: strstr

Combine with substr to strip out your token:

$out = substr(strstr($text, 'ABC'), strlen('ABC'))

how to delete certain characters from a string in php

There are a few easy ways to tackle this problem.

Consider Replacing Prior to Exploding

The first could be to simply perform your str_replace() call prior to the explode() function :

# Explicitly replace your input
$input = str_replace($_SERVER["REQUEST_URI"],'/sfm?dir=uploads/sfm/','');
# Then explode as expected
$crumbs = explode("/", $input);

Slice Off The First Two Elements

Another option would be to simply slice your original array and remove the first two elements from it via the array_slice() function:

# Explode your string into an array
$crumbs = explode("/", $_SERVER["REQUEST_URI"]);
# Trim off the first two elements of the array
$crumbs = array_slice($crumbs,2)

Best way to replace/remove a specific character when it appears between 2 character sequences

So it was a good thing I asked for the output, because initially I had something else. Many people would use regular expressions here, but I often find those difficult to work with, so I took a more basic approach:

function extractWantedStuff($input)
{
$output = [];
$sections = explode('""', $input);
$changeThisSection = false;
foreach ($sections as $section) {
if ($changeThisSection) {
$section = str_replace(',', '', $section);
}
$output[] = $section;
$changeThisSection = !$changeThisSection;
}
return implode('""', $output);
}

$fullstring = ',""Word1, Word2"" and another thing ,""Word3, Word4""';

echo extractWantedStuff($fullstring);

The output would be:

,""Word1 Word2"" and another thing ,""Word3 Word4""

See: Example code

Slightly more optimized, by removing the $changeThisSection boolean:

function extractWantedStuff($input)
{
$output = [];
$sections = explode('""', $input);
foreach ($sections as $key => $section) {
if ($key % 2 != 0) { // is $key uneven?
$section = str_replace(',', '', $section);
}
$output[] = $section;
}
return implode('""', $output);
}

$fullstring = ',""Word1, Word2"" and another thing ,""Word3, Word4""';

echo extractWantedStuff($fullstring);

See: Example code

And further optimized, by removing the $output array:

function extractWantedStuff($string)
{
$sections = explode('""', $string);
foreach ($sections as $key => $section) {
if ($key % 2 != 0) {
$sections[$key] = str_replace(',', '', $section);
}
}
return implode('""', $sections);
}

$fullstring = ',""Word1, Word2"" and another thing ,""Word3, Word4""';

echo extractWantedStuff($fullstring);

See: Example code

Remove all special characters from a string

This should do what you're looking for:

function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

Usage:

echo clean('a|"bc!@£de^&$f g');

Will output: abcdef-g

Edit:

Hey, just a quick question, how can I prevent multiple hyphens from being next to each other? and have them replaced with just 1?

function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}

PHP 'Delete all between' specific words

Use the preg_replace()-function

$result = preg_replace('/product\s+code[^>]*\>/is', '', $input);

Regular Expression

look for    "product"
followed by \s+ (one or more spaces, tabs,...)
followed by "code"
followed by [^>]* (an unspecified amount of charakters that are not ">")
followed by \> an ">" (\ is es for escaping)

Flag

i = ignore upper/lowercase
s = search multiple lines

Methods to remove specific characters from string?

There are several methods available, and they can sometimes be made to perform exactly the same task, like preg_replace/str_replace. But, perhaps you want to remove brackets only from the beginning or end of the string; in which case preg_replace works. But, if there could be several brackets, preg_replace can do the job too. But trim is easier and makes more sense.

preg_replace() - removes beginning and trailing brackets

$widget_id = preg_replace(array('/^\[/','/\]$/'), '',$widget_text);      

str_replace() - this removes brackets anywhere in the text

$widget_id = str_replace(array('[',']'), '',$widget_text);

trim() - trims brackets from beginning and end

$widget_id = trim($widget_text,'[]')

substr() - does the same as trim() (assuming the widget text does not include any closing brackets within the text)

$widget_id = substr($widget_text,
$start = strspn($widget_text, '['),
strcspn($widget_text, ']') - $start
);

Remove everything up to and including character in PHP string

This can be achieved using string manipulation functions in PHP. First we find the position of the - character in the string using strpos(). Use substr() to get everything until that character (including that one). Then use trim() to remove whitespace from the beginning and/or end of the string:

echo trim(substr($str, strpos($str, '-') + 1)); // => £20.00

Alternatively, you could split the string into two pieces, with - as the delimiter, and take the second part:

echo trim(explode('-', $str)[1]);

This could be done in many different ways. In the end, it all boils down to your preferences and requirements.



Related Topics



Leave a reply



Submit