Solved

Function to Remove several words from php string

Posted on 2011-09-28
2
184 Views
Last Modified: 2012-06-21
Hi,

I have this:

$remove1 = "pdf"
$remove2="donwload"

$str="Download Adobe Dreamweaver training PDF"

Result should be:
$str="Adobe Dreamweaver training"

Can someone help me with a simple function to remove several word from string ?

It would be nice to call the function this way:
<?php echo $mystring("donwload","pdf") ?>

Thank you for any help!
0
Comment
Question by:Fernanditos
2 Comments
 
LVL 8

Expert Comment

by:Rik-Legger
ID: 36718011
function remove ($needles, $haystack) {
   return str_replace($needles, '', $haystack);
}


echo remove(array('download','pdf'), 'Download Adobe Dreamweaver training PDF');

Open in new window


Not tested, but something like this will work.
0
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 36718927
http://www.laprbass.com/RAY_temp_fernanditos.php
<?php // RAY_temp_fernanditos.php
error_reporting(E_ALL);
echo "<pre>";

// TEST DATA
$str="Download Adobe Dreamweaver training PDF";

// THE THINGS WE DO NOT WANT
$xxx = array
( "pdf"
, "download"
, "nonsense"
)
;

// A FUNCTION DEFINITION
function cleanup($str, $xxx)
{
    // CREATE A REGULAR EXPRESSION TO HANDLE CASE-INSENSITIVE REPLACEMENT
    $regex
    = '#'         // REGEX DELIMITER
    . '('         // START OF GROUP
    . implode('|', $xxx)
    . ')'         // END OF GROUP
    . '#'         // REGEX DELIMITER
    . 'i'         // CASE-INSENSITIVE
    ;

    return trim(preg_replace($regex, NULL, $str));
}
// SHOW THE WORK
echo cleanup($str, $xxx);

Open in new window

0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question