PHP preg_replace - php

*strong text*i have a string like that "x", "x,y" , "x,y,h"
i want to user preg replace to remove the commas inside the double qutations and return the string as
"x", "xy" , "xyh"

You can just use a regular replace.
$mystring = str_replace(",", "", $mystring);

You dont need preg_replace() here and whereever possible you should trying to avoid it
$string = str_replace(',', '', $string);

This would work fine: http://codepad.org/lq7I5wkd
<?php
$myStr = '"x", "x,y" , "x,y,h"';
$chunks = preg_split("/\"[\s]*[,][\s]*\"/", $myStr);
for($i=0;$i<count($chunks);$i++)
$chunks[$i] = str_replace(",","",$chunks[$i]);
echo implode('","',$chunks);
?>

I use the following, which I've found is generally faster than regexp for this type of replacement
$string = '"x", "x,y" , "x,y,h"';
$temp = explode('"',$string);
$i = true;
foreach($temp as &$value) {
// Only replace in alternating array entries, because these are the entries inside the quotes
if ($i = !$i) {
$value = str_replace(',', '', $value);
}
}
unset($value);
// Then rebuild the original string
$string = implode('"',$temp);

Related

Uppercase for first letter with php

How can I convert to uppercase for the following example :
title-title-title
Result should be:
Title-Title-Title
I tried with ucwords but it converts like this: Title-title-title
I currently have this:
echo $title = ($this->session->userdata('head_title') != '' ? $this->session->userdata('head_title'):'Our Home Page');
In this particular string example, you could explode the strings first, use that function ucfirst() and apply to all exploded strings, then put them back together again:
$string = 'title-title-title';
$strings = implode('-', array_map('ucfirst', explode('-', $string)));
echo $strings;
Should be fairly straightforward on applying this:
$title = '';
if($this->session->userdata('head_title') != '') {
$raw_title = $this->session->userdata('head_title'); // title-title-title
$title = implode('-', array_map('ucfirst', explode('-', $raw_title)));
} else {
$title = 'Our Home Page';
}
echo $title;
echo str_replace(" ","-",ucwords(str_replace("-"," ","title-title-title")));
Fiddle
Output:
Title-Title-Title
Demo
Not as swift as Ghost's but a touch more readable for beginners to see what's happening.
//break words on delimiter
$arr = explode("-", $string);
//capitalize first word only
$ord = array_map('ucfirst', $arr);
//rebuild the string
echo implode("-", $ord);
The array_map() applies callback to the elements of the given array. Internally, it traverses through the elements in our word-filled array $arr and applies the function ucfirst() to each of them. Saves you couple of lines.
Edit #2
This isn't working for the new information added to op, as there is an answer this won't be updated to reflect that.
Edit #1
$var = "title-title-title";
$var = str_replace (" ", "_", ucwords (str_replace (" ", "_", $var));
Old, non-working
$var = "title-title-title";
$var = implode("-", ucwords (explode("-", $var)));
try the following:
$str='title-title-title';
$s='';
foreach(explode('-',$str) as $si){
$s.= ($s ? "-":"").ucfirst($si);
}
$s should be Title-Title-Title at this point

PHP adding the value 1 to a position in an string and replace

I want to replace a letter with another character and also add 1 value more.
I mean the values are dynamic
For example I have H9 ,i want to replace as G10 .
Similarly...
H2 as G3
H6 as G7
Is it possible to use str_replace() for this ?
I got this one which works for me:
$old_string = "H2";
$new_string = "G" . (substr($old_string, 1) + 1);
echo $new_string;
Works fine for me. This is just for one value, but i guess you can loop through an array too, just have to modify the values like this
foreach($old_values as $v) {
$new_values[] = "G" . (substr($v, 1) + 1);
}
So you could save all the values into the $new_string array
Try This
<?php
$str = "H25";
preg_match_all('!\d+!', $str, $matches);
$str = str_replace($matches['0']['0'], $matches['0']['0']+1, $str, $count);
echo $str;
?>
Of course you can use str_replace()
Use
$new = array("G10", "G3", "G7");
$old = array("H9", "H2", "H6");
$string = str_replace($old, $new, $string);
where $string is your original string.
More simpler way... (Generalized Solution)
<?php
$str='G10';
preg_match('!\d+!', $str, $digit); //<---- Match the number
$str = substr($str,0,1); //<--- Grab the first char & increment it in the second line
echo ++$str.($digit[0]+1); //"prints" H11
Demo

PHP function that convert 'a,b' to ' "a","b" ' [duplicate]

This question already has answers here:
Add quotation marks to comma delimited string in PHP
(5 answers)
Closed 1 year ago.
I have a variable with string value of 'laptop,Bag' and I want it to look like ' "laptop","Bag" 'or "laptop","Bag". How could I do this one? Is there any php function that could get this job done? Any help please.
This would work. It first, explodes the string into an array. And then implodes it with speech marks & finishes up by adding the opening & closing speech mark.
$string = "laptop,bag";
$explode = explode(",", $string);
$implode = '"'.implode('","', $explode).'"';
echo $implode;
Output:
"laptop","bag"
That's what str_replace is for:
$result = '"'.str_replace(',', '","', $str).'"';
This would be very easy to do.
$string = 'laptop,bag';
$items = explode(',', $string);
$newString = '"'.implode('","', $items).'"';
That should turn 'laptop,bag' into "laptop","bag".
Wrapping that in a function would be as simple as this:
function changeString($string) {
$items = explode(',', $string);
$newString = '"'.implode('","', $items).'"';
return $newString;
}
I think you can explode your string as array and loop throw it creating your new string
function create_string($string)
{
$string_array = explode(",", $string);
$new_string = '';
foreach($string_array as $str)
{
$new_string .= '"'.$str.'",';
}
$new_string = substr($new_string,-1);
return $new_string;
}
Now you simply pass your string the function
$string = 'laptop,Bag';
echo create_string($string);
//output "laptop","Bag"
For your specific example, this code would do the trick:
<?php
$string = 'laptop,bag';
$new_string = ' "' . str_replace(',', '","', $string) . '" ';
// $new_string: "laptop","bag"
?>
That code would also work if you had more items in that list, as long as they are comma-separated.
Use preg_replace():
$input_lines="laptop,bag";
echo preg_replace("/(\w+)/", '"$1"', $input_lines);
Output:
'"laptop","Bag"'
I think you can perform that using explode in php converting that string in to an array.
$tags = "laptop,bag";
$tagsArray = explode(",", $tags);
echo $tagsArray[0]; // laptop
echo $tagsArray[1]; // bag
Reference
http://us2.php.net/manual/en/function.explode.php
related post take a look maybe could solve your problem.
How can I split a comma delimited string into an array in PHP?

list of all PHP preg_replace characters to escape

Where can find a list of all characters that must be escaped when using preg_replace. I listed what I think are three of them in the array $ESCAPE_CHARS. What other ones am I missing.
I need this because I am going to be doing a preg replace on a form submission.
So ie.
$ESCAPE_CHARS = array("#", "^", "[");
foreach ($ESCAPE_CHARS as $char) {
$_POST{"string"} = str_replace("$char", "\\$char", $_POST{"string"});
}
$string = $_POST{"string"};
$test = "string of text";
$test = preg_replace("$string", "<b>$string</b>", $test);
Thanks!
You can use preg_quote():
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
print $keywords;
// \$40 for a g3\/400

PHP - Strip a specific string out of a string

I've got this string, but I need to remove specific things out of it...
Original String: hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64.
The string I need: sh-290-92.ch-215-84.lg-280-64.
I need to remove hr-165-34. and hd-180-1.
!
EDIT: Ahh ive hit a snag!
the string always changes, so the bits i need to remove like "hr-165-34." always change, it will always be "hr-SOMETHING-SOMETHING."
So the methods im using wont work!
Thanks
Depends on why you want to remove exactly those Substrigs...
If you always want to remove exactly those substrings, you can use str_replace
If you always want to remove the characters at the same position, you can use substr
If you always want to remove substrings between two dots, that match certain criteria, you can use preg_replace
$str = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
$new_str = str_replace(array('hr-165-34.', 'hd-180-1.'), '', $str);
Info on str_replace.
The easiest and quickest way of doing this is to use str_replace
$ostr = "hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64";
$nstr = str_replace("hr-165-34.","",$ostr);
$nstr = str_replace("hd-180-1.","",$nstr);
<?php
$string = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
// define all strings to delete is easier by using an array
$delete_substrings = array('hr-165-34.', 'hd-180-1.');
$string = str_replace($delete_substrings, '', $string);
assert('$string == "sh-290-92.ch-215-84.lg-280-64" /* Expected result: string = "sh-290-92.ch-215-84.lg-280-64" */');
?>
Ive figured it out!
$figure = $q['figure']; // hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64
$s = $figure;
$matches = array();
$t = preg_match('/hr(.*?)\./s', $s, $matches);
$s = $figure;
$matches2 = array();
$t = preg_match('/hd(.*?)\./s', $s, $matches2);
$s = $figure;
$matches3 = array();
$t = preg_match('/ea(.*?)\./s', $s, $matches3);
$str = $figure;
$new_str = str_replace(array($matches[0], $matches2[0], $matches3[0]), '', $str);
echo($new_str);
Thanks guys!

Categories