69260

Remove first and last instance of a string?

Question:

How can I remove the <strong>first</strong> instance of a certain piece of html from a string.

I'm looking to remove

</tr> </table></td> </tr

which is near the begining, but it also appears throughout the string.

I also need a way to do the same thing but the <strong>last</strong> instance of it.

Anyone know?

Answer1:

if you know roughly how close to the end of the string the substring that you want to replace is, you use substr_replace() with a negative $start and $length parameters, or you could just code up a function by hand to actually go through, find the last occurrence, then delete it. something like this (untested, written very quickly):

function replace_last_occurrence($haystack, $needle) { $pos = 0; $last = 0; while($pos !== false) { $pos = strpos($haystack, $needle, $pos); $last = $pos; } substr_replace($haystack, "", $last, strlen($needle)); }

similar, for first occurrence

function replace_first_occurrence($haystack, $needle) { substr_replace($haystack, "", strpos($haystack, $needle, $pos), strlen($needle)); }

you could also generalize this to replace the nth occurrence:

function replace_nth_occurrence($haystack, $needle, $n) { $pos = 0; $last = 0; for($i = 0 ; $i <= $n ; $i++) { $pos = strpos($haystack, $needle, $pos); $last = $pos; } substr_replace($haystack, "", $last, strlen($needle)); }

Answer2:

simplest way is to explode/split the string shift the top and pop the last then implode what's left with you're separator and concatenate the three.. i.e.:

$separator = 'your specified html separator here'; $bits = explode($separator , $yourhtml ); $start = array_shift($bits); $end = array_pop($bits); $sorted = $start . implode($separator,$bits) . $end;

(not tested)

Answer3:

This will delete last occurrence:

$needle = <<<EON </tr> </table></td> </tr EON; if(preg_match('`.*('.preg_quote($needle).')`s', $haystack, $m, PREG_OFFSET_CAPTURE)) { $haystack = substr_replace($haystack, '', $m[1][1], strlen($m[1][0])); }

As additional bonus you may ignore varying number of whitespaces within searched fragment like this:

if(preg_match('`.*('.implode('\s+', array_map('preg_quote', preg_split('`\s+`', $needle))).')`s', $haystack, $m, PREG_OFFSET_CAPTURE)) { $haystack = substr_replace($haystack, '', $m[1][1], strlen($m[1][0])); }

Or even search case-insensitively by adding i-flag to regexp:

if(preg_match('`.*('.implode('\s+', array_map('preg_quote', preg_split('`\s+`', $needle))).')`is', $haystack, $m, PREG_OFFSET_CAPTURE)) { $haystack = substr_replace($haystack, '', $m[1][1], strlen($m[1][0])); }

Answer4:

You'll be wanting <a href="http://php.net/manual/en/function.str-replace.php" rel="nofollow">str_replace</a>. Replace that section with empty space (eg:"")

Recommend

  • Nofollow on links in CKEditor
  • Unix:Recursively unzipping .zip file in respective folder
  • Better way to move MongoDB Collection to another Collection
  • Is there any way to convert json to xml in PHP?
  • How to prevent Console Application from terminating when pressing “Ctrl+C” in C?
  • Controlling tab space in a using CSS?
  • console.log printing statements in the wrong order for learnyounode node.js tutorial
  • DML and Exception Handling - Oracle
  • Where in the relevant specification is it documented that some comments in a SQL script are, in fact
  • react native create element with string
  • Avoid registering duplicate broadcast receivers in Android
  • Get the number 18437736874454810627
  • Angular2 - Template reference inside NgSwitch
  • How can I run DataNucleus Bytecode Enhancer from SBT?
  • How to handle elastic beanstalk deployment so it uploads only changed files
  • JSR-330 support in Picocontainer : @Inject … @Named(\"xxx)
  • Jquery Knockout: ko.computed() vs classic function?
  • Check all values in string[] for length?
  • Insert new calendar with SyncAdapter- Calendar API Android
  • Ensure fsync did its job
  • How to define and use opencv mat of user type
  • why overloaded new operator is calling constructor even I am using malloc inside overloading functio
  • If I include Java 8 in my Android app does that affect which devices it will work on?
  • Adding a button at the bottom of a table view
  • Getting last autonumber in access
  • Azure Cloud Service Web Role web pages do not load
  • Delete MySQLi record without showing the id in the URL
  • GridView Sorting works once only
  • R: gsub and capture
  • Benchmarking RAM performance - UWP and C#
  • Acquiring multiple attributes from .xml file in c#
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • How can I remove ASP.NET Designer.cs files?
  • Reading document lines to the user (python)
  • Binding checkboxes to object values in AngularJs
  • How can i traverse a binary tree from right to left in java?
  • java string with new operator and a literal
  • Net Present Value in Excel for Grouped Recurring CF
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?