Solved

php substring remove between --

Posted on 2012-04-02
5
248 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
Comment Utility
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
Comment Utility
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
Comment Utility
<?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
Comment Utility
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
Comment Utility
Because of you have replaced "-" to " " already. Swap line 2 and 3 and see the result.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

762 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now