PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

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

 November 20, 2022     php, preg-replace, replace     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing