Sunday, November 20, 2022

[FIXED] How to remove substring from PHP $var?

Issue

When using PHP, how can I remove the characters between two forward slashes in a $var?

I tried:

$test = "gdgfdgdf/asg8&7_09()9/87iuyiuuyty";
$test = str_replace('/\s+/', '_', $test);

Note that /asg8&7_09()9/ is dynamic data.

Unfortunately this doesn't give the intended results. How can I accomplish this using PHP?


Solution

Your question isn't exactly clear on if you want to remove just what is between the slashes, or the slashes as well.

$test = "gdgfdgdf/asg8&7_09()9/87iuyiuuyty";
$test = preg_replace( '/\/.*?\//', '_', $test );
print_r( $test );

Result

gdgfdgdf_87iuyiuuyty

This code removes the slashes and their content. For the slashes to persist after processing, you could make the replacement '/_/'

$test = preg_replace( '/\/.*?\//', '/_/', $test );

Result

gdgfdgdf/_/87iuyiuuyty


Within the match pattern

. Match any character (except newline)
* Match 0 or more times

Regex Pal demonstration



Answered By - domwrap
Answer Checked By - Terry (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.