How to remove string with comma in a big string? - php

I'm a newbie in PHP ,andnow I'm struck on this problem . I have a string like this :
$string = "qwe,asd,zxc,rty,fgh,vbn";
Now I want when user click to "qwe" it will remove "qwe," in $string
Ex:$string = "asd,zxc,rty,fgh,vbn";
Or remove "fhg,"
Ex:$string = "asd,zxc,rty,vbn";
I try to user str_replace but it just remove the string and still have a comma before the string like this:
$string = ",asd,zxc,rty,fgh,vbn";
Anyone can help? Thanks for reading

Try this out:
$break=explode(",",$string);
$new_array=array();
foreach($break as $newData)
{
if($newData!='qwe')
{
$new_array[]=$newData;
}
}
$newWord=implode(",",$new_array);
echo $newWord;

In order to achieve your objective, array is your best friend.
$string = "qwe,asd,zxc,rty,fgh,vbn";
$ExplodedString = explode( "," , $string ); //Explode them separated by comma
$itemToRemove = "asd";
foreach($ExplodedString as $key => $value){ //loop along the array
if( $itemToRemove == $value ){ //check if item to be removed exists in the array
unset($ExplodedString[$key]); //unset or remove is found
}
}
$NewLook = array_values($ExplodedString); //Re-index the array key
print_r($NewLook); //print the array content
$NewLookCombined = implode( "," , $NewLook);
print_r($NewLookCombined); //print the array content after combined back

here the solution
$string = "qwe,asd,zxc,rty,fgh,vbn";
$clickword = "vbn";
$exp = explode(",", $string);
$imp = implode(" ", $exp);
if(stripos($imp, $clickword) !== false) {
$var = str_replace($clickword," ", $imp);
}
$str = preg_replace('/\s\s+/',' ', $var);
$newexp = explode(" ", trim($str));
$newimp = implode(",", $newexp);
echo $newimp;

You could try preg_replace http://uk3.php.net/manual/en/function.preg-replace.php if you have the module set up. It will allow you to optionally replace trailing or leading commas easily:
preg_replace("/,*$providedString,*/i", '', "qwe,asd,zxc,rty,fgh,vbn");

Related

Insert some text after the second forward slash in a php string?

I've been working with this code
<?php
class PerchTemplateFilter_sol_en_cat_path extends PerchTemplateFilter {
public function filterAfterProcessing($value, $valueIsMarkup = false) {
// ORIGINAL STRING: solutions-en/rail-technologies/track-components/name-of-product
$mystring = $value;
$replace = ['solutions-en', '%2F'];
$str = '';
$oldstr = str_replace($replace, $str, $mystring);
$str_to_insert = 'XXX';
$findme = '/';
$pos = strpos($mystring, $findme); // I NEED THIS TO INSERT $str_to_insert AFTER THE SECOND FORWARD SLASH FOUND IN THE ORIGINAL STRING?
$value = substr_replace($oldstr, $str_to_insert, $pos, 0);
return $value;
// $value: /rail-technologies/track-components/XXX/name-of-product
// Insert string at specified position
// https://stackoverflow.com/questions/8251426/insert-string-at-specified-position
}
}
PerchSystem::register_template_filter('sol_en_cat_path', 'PerchTemplateFilter_sol_en_cat_path');
?>
My string is: solutions-en/rail-technologies/track-components/name-of-product
I want to end up with: /rail-technologies/XXX/track-components/name-of-product
XXX is only a placeholder value
I guess I need to do something with $pos to set where I want XXX to be added to the string.
I need to insert after the second forward slash, as the string may contain different text
The code above outputs this string: /rail-technoXXXlogies/track-components/ewosr-switch-lock
I can't seem to figure out how to insert XXX after the second forward slash.
Hope someone can provide some help.
How about explode to array, then implode the first two items.
Join with xxx and implode the rest?
function AddInTheMiddle($start, $where, $what){
$arr = explode("/", $what);
$str = implode("/", array_splice($arr,$start,$where)) . '/xxx/' . implode("/", $arr);;
return $str;
}
$str = 'solutions-en/rail-technologies/track-components/name-of-product';
$str = AddInTheMiddle(1, 2, $str);
https://3v4l.org/m98io
Thank you Andreas, your post gave me the nudge I needed. I did this in the end.
// ORIGINAL $value: solutions-en/rail-technologies/track-components/name-of-product
$str = explode("/", $value);
$value = $str[1] . '/' . 'solutions' . '/' . $str[2] . '/';
return $value;
// Removed: solutions-en
// Added: solutions
// $value: rail-technologies/solutions/track-components/name-of-product
I was able to add the name-of-product to the end of the new string elsewhere in my template.

Extract specific word from a string

It might seem easy to do but I have trouble extracting this string. I have a string that has # tags in it and I'm trying to pull the tags maps/place/Residences+Jardins+de+Majorelle/#33.536759,-7.613825,17z/data=!3m1!4b1!4m2!3m1!1s0xda62d6053931323:0x2f978f4d1aabb1aa
And here is what I want to extract 33.536759,-7.613825,17z :
$var = preg_match_all("/#(\w*)/",$path,$query);
Any way I can do this? Much appreciated.
Change your regex to this one: /#([\w\d\.\,-]*)/.
This will return the string beginning with #.
$string = 'maps/place/Residences+Jardins+de+Majorelle/#33.536759,-7.613825,17z/data=!3m1!4b1!4m2!3m1!1s0xda62d6053931323:0x2f978f4d1aabb1aa';
$string = explode('/',$string);
//$coordinates = substr($string[3], 1);
//print_r($coordinates);
foreach ($string as $substring) {
if (substr( $substring, 0, 1 ) === "#") {
$coordinates = $substring;
}
}
echo $coordinates;
This is working for me:
$path = "maps/place/Residences+Jardins+de+Majorelle/#33.536759,-7.613825,17z/data=!3m1!4b1!4m2!3m1!1s0xda62d6053931323:0x2f978f4d1aabb1aa";
$var = preg_match_all("/#([^\/]+)/",$path,$query);
print $query[1][0];
A regex would do.
/#(-*\d+\.\d+),(-*\d\.\d+,\d+z*)/
If there is only one # and the string ends with / you can use the following code:
//String
$string = 'maps/place/Residences+Jardins+de+Majorelle/#33.536759,-7.613825,17z/data=!3m1!4b1!4m2!3m1!1s0xda62d6053931323:0x2f978f4d1aabb1aa';
//Save string after the first #
$coordinates = strstr($string, '#');
//Remove #
$coordinates = str_replace('#', '', $coordinates);
//Separate string on every /
$coordinates = explode('/', $coordinates );
//Save first part
$coordinates = $coordinates[0];
//Do what you want
echo $coordinates;
do like this
$re = '/#((.*?),-(.*?),)/mi';
$str = 'maps/place/Residences+Jardins+de+Majorelle/#33.536759,-7.613825,17z/data=!3m1!4b1!4m2!3m1!1s0xda62d6053931323:0x2f978f4d1aabb1aa';
preg_match_all($re, $str, $matches);
echo $matches[2][0].'<br>';
echo $matches[3][0];
output
33.536759
7.613825

how do you parse out a text value in php

I have a line like this:
$line1= "System configuration: lcpu=96 mem=393216MB ent=16.00"
I need to parse out lcpu, mem and ent values from this string. I have tried something like this:
$lcpu=preg_match('/(?P<lcpu>\w+)= (?P<digit>\d+)/', $line1, $matches);
does not seem to be getting the lcpu values from the string $line1, any ideas what I am doing wrong here?
You've nearly got a query string there, so maybe
$string = explode(": ", $line1);
$string = str_replace(" ", "&", $string[1]);
parse_str($string, $values);
echo $values['lcpu'];
One other way to pares strings:
$line1= "System configuration: lcpu=96 mem=393216MB ent=16.00";
list($lcpu, $mem, $ent) = sscanf($line1, "System configuration: lcpu=%d mem=%dMB ent=%f");
Why not use a simple function to get the string between two strings. If the lcpu value is always going to be prefixed by "lcpu=" and end with a " " (space) then you could use:
function getBetween($str, $start, $end)
{
$r = explode($start, $str);
if (isset($r[1]))
{
$r = explode($end, $r[1]);
return $r[0];
}
return false;
}
and just say:
if (getBetween($line1, 'lcpu=', ' ')) { ... }
It'll return false if nothing is found.
Personally, I would parse by syntax instead (rather than searching for specific keys):
<?php
$input = "System configuration: lcpu=96 mem=393216MB ent=16.00";
// Strip out "System configuration: "
$values = preg_replace('~^.*?:\s*$~', '', $input);
// Split on whitespace separator
$values = preg_split('~\s+~', $values);
// Convert to associative array
foreach ($values as $i => $item)
{
// Explode on assignment (=)
list($k, $v) = explode('=', $item);
$values[$k] = $v;
unset($values[$i]);
}
There are many ways to parse a string. Explode is usually faster than using a regex, so this way may be more performant than the methods which rely on regular expressions.
list( , , $lcpu_pair )= explode( " ", $line1 );
list( , $lcpu_value ) = explode( "=", $lcpu_pair );
$lcpu_value will contain '96'.

How to remove unwanted commas from a string?

How can i remove duplicate commas used in string.
String = ",a,b,c,,,d,,"
I tried rtrim and itrim functions and removed the unwanted commas from beginning and ending .How can i remove duplicate commas ?
Try this:
$str = preg_replace('/,{2,}/', ',', trim($str, ','));
The trim will remove starting and trailing commas, while the preg_replace will remove duplicate ones.
See it in action!
Also, as #Spudley suggested, the regex /,{2,}/ could be replaced with /,,+/ and it would work too.
EDIT:
If there are spaces between commas, you may try adding the following line after the one above:
$str = implode(',', array_map('trim', explode(',', $str)))
i think you can just explode your string and then create a new one getting only relevant data
$string = ",a,b,c,,,d,,";
$str = explode(",", $string);
$string_new = '';
foreach($str as $data)
{
if(!empty($data))
{
$string_new .= $data. ',';
}
}
echo substr_replace($string_new, '', -1);
This will output
a,b,c,d
Live Demo
EDITED
If you are having problems with blank spaces you can try use this code
$string = ",a,b,c, ,,d,,";
$str = explode(",", str_replace(' ', '', $string));
$string_new = '';
foreach($str as $data)
{
if(!empty($data))
{
$string_new .= $data. ',';
}
}
echo substr_replace($string_new, '', -1);
This should solve spaces issue
Probably not very fast, but a simple method may be:
$str = "a,b,c,,,d";
$str2 = "";
while($str <> $str2) {
$str2 = $str;
$str = str_replace(',,', ',', $str);
}
<?php
$str = ",a,b,c,,,d,,"
echo $str=str_replace(',,','',$str);
?>
Output:
,a,b,c,d
<?php
$str = ",a,b,c,,,d,,"
echo $str=trim(str_replace(',,','',$str),',');
?>
Output:
a,b,c,d

Convert comma separated string into array

I have a comma separated string, which consists of a list of tags and want to convert it to array to get a link for every tag.
Example:
$string = 'html,css,php,mysql,javascript';
I want to make it like this:
html, css, php, mysql, javascript
So the result will be a string containing comma separated links with a space after each link and with no comma after the last link.
I have this function where $arg = 'html,css,php,mysql,javascript':
function info_get_tags( $arg ) {
global $u;
$tagss = '';
if ( $arg == '' ) {
return '';
} else {
$tags_arr = explode( ',' , $arg );
foreach ( $tags_arr as $tag ) {
$tags = '' . $tag . '';
$tagss .= $tags;
}
return $tagss;
}
}
This script works for me but without commas and spaces and if we add a comma and a space here:
$tags = '' . $tag . ', ';
we get commas and spaces but there will be a trailing comma after the last link.
Just like you exploded you can implode again:
$tags = explode(',', $arg);
foreach ($tags as &$tag) {
$tag = '' . $tag . '';
}
return implode(', ', $tags);
Here's an alternative that uses array_map instead of the foreach loop:
global $u;
function add_html($tag){
return('' . $tag . '');
}
function get_tags($taglist){
$tags_arr = array_map("add_html", explode( ',' , $taglist));
return implode(", " , $tags_arr);
}
Try this short code
$string = 'html,css,php,mysql,javascript';
$string = explode(',', $string);
   foreach( $string as $link){
   echo ''.$link.'';
}
Easiest way is to the html into an array (each tag link is an array element) and then implode on ,...
if ( $arg == '' ) {
return '';
} else {
$tags_arr = explode( ',' , $arg );
$tags = array();
$tagtpl = '%s';
foreach ( $tags_arr as $tag ) {
$url = $u . 'tag/' . $tag . '/';
$tags[] = sprintf($tagtpl, $url, $tag, $tag);
}
return implode(', ', $tags);
}
Try this
$tagss = trim($tagss);
return substr($tagss, 0 , strlen($tagss)-1);
Why not put all tags in an array when you are creating them, and later explode the array and add the commas and spaces between the tags.
foreach ( $tags_arr as $tag ) {
$tags = '' . $tag . '';
$tagss[] = $tags;
}
$tagss = explode(', ', $tagss);
The workaround(!) would be to remove the unwanted trailing characters afterwards:
$tagss = rtrim($tagss, ", ");
This rtrim removes any mix of spaces and commas from the right end of the string.
Btw, you could use str_getcsv instead of explode, which also handles input spaces better.
function info_get_tags($arg)
{
global $u;
if (empty($arg)) return '';
return ltrim(preg_replace('/([^\,]+)/', ' ${1}', $arg));
}
$string = 'html,css,php,mysql,javascript';
puts $string.split(/,/).map { |tag| "#{tag}"}.join(", ")
result:
html, css, php, mysql, javascript
Another solution:
$html = trim(preg_replace('/([^,]+)/', ' \1', $string));
Or if you have to html encode the tags (always smart, since you're creating html from text):
$html = trim(preg_replace_callback('/([^,]+)/', function($match) {
$tag = $match[1];
return ' ' . htmlspecialchars($tag) . '';
}, $string));
So this $string would work too: "tag with space,html,css,php,mysql,javascript"
More regex is always good!

Categories