Solved

php substring remove between --

Posted on 2012-04-02
5
252 Views
Last Modified: 2012-06-27
I need to remove a string that is in between "--" (double dash) of a long string.

this-is-a-string--REMOVE--this-is-another-string

Open in new window

0
Comment
Question by:glynco
5 Comments
 
LVL 15

Expert Comment

by:gplana
ID: 37795270
try this:
$your_string = "this-is-a-string--REMOVE--this-is-another-string";
$pos = strpos($your_string,'--');
$left_part = substr($your_string,0,$pos-1);
$pos = strpos($your_string, '--', $pos+2);
$right_part = substr($your_string, $pos+2);
$your_string = $left_part . $right_part;

Open in new window

0
 
LVL 17

Expert Comment

by:sonawanekiran
ID: 37795283
Try like this
$str = "this-is-a-string--REMOVE--this-is-another-string";
echo preg_replace('/--+/','',$str);
OR

echo preg_replace('/[-]{2,}/','',$str);
0
 
LVL 15

Accepted Solution

by:
StingRaY earned 500 total points
ID: 37795293
<?php

$string = 'this-is-a-string--REMOVE--this-is-another-string--REMOVE ME TOO--the-rest-of-string';
$string = preg_replace('/(--)(.*)(--)/U','$1$3',$string);
echo $string;

?>

Open in new window


Result:

this-is-a-string----this-is-another-string----the-rest-of-string
0
 

Author Comment

by:glynco
ID: 37795344
StingRay when I change the string to something like this. The --coins-currency-- is not removed.

$string = '2012-04-02-165747--coins-currency--coins-title';
$string = substr(str_replace("-"," ", $string), 18);
$string = preg_replace('/(--)(.*)(--)/U','$1$3',$string);
echo $string;

Open in new window

0
 
LVL 15

Expert Comment

by:StingRaY
ID: 37795370
Because of you have replaced "-" to " " already. Swap line 2 and 3 and see the result.
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
This article discusses four methods for overlaying images in a container on a web page
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.

832 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