Replace multiple items in a string - php

i've scraped a html string from a website. In this string it contains multiple strings like color:#0269D2. How can i make str_replace code which replace this string with another color ?
For instance something like this just looping through all color:#0269D in the fulltext string variable?
str_replace("color:#0269D","color:#000000",$fulltext);

you pass array to str_replace function , no need to use loop
$a= array("color:#0269D","color:#000000");
$str= str_replace($a,"", $string);

You have the right syntax. I would add a check:
$newText = str_replace("color:#0269D", "color:#000000", $fulltext, $count);
if($count){
echo "Replaced $count occurrences of 'color'.";
}
This code might be too greedy for what you're looking to do. Careful. Also if the string differs at all, for example color: #0269D, this replacement will not happen.

’str_replace’ already replaces all occurrences of the search string with the replacement string.
If you want to replace all colors but aren't sure which hexcodes you'll find you could use preg_replace to match multiple occurrences of a pattern with a regular expression and replace it.
In your case:
$str = "String with loads of color:#000000";
$pattern = '/color ?: ?#[0-9a-f]{3,6}/i';
$replacement = "color:#FFFFFF";
$result = preg_replace($pattern, $replacement, $str);

Related

Regex to replace a string from one place to another in the same record

I have a record separated by | symbol. I need to replace a string from one place to another in the same record:
My input looks like this:
BANG|ADAR|**285815**|MOTOR|GOOD||INDIA|2.4|SOFTWARE|285816_AKS|SAB_PART|**AKS_PN|285816**
I need to replace 285815 with the string after AKS_PN, in this case I need to replace 285815 with 285816.
With the (([^|]*\|){3})(.*) I am able to fetch 285815, need help in fetching string after AKS_PN in the same regular expression.
I am aware of how to replace 285815 with 285816. I am using PHP.
Regex solution
You need to use capturing groups. In general:
(everything_before)(interesting_part_1)(between)(interesting_part_in_the_end)
Afterwards, just put it together as you wish
(everything_before)(interesting_part_in_the_end)(between)
This leaves (interesting_part_1) out of the final string.
In your specific example this might come down to
^((?:[^|]*\|){2})([^|]*)\|(.*?AKS_PN)\|(.*)
which would need to be replaced by
$1$4|$3
See an example on regex101.com (still not sure what to do with 285815 here).
Everything in PHP:
<?php
$string = "BANG|ADAR|285815|MOTOR|GOOD||INDIA|2.4|SOFTWARE|285816_AKS|SAB_PART|AKS_PN|285816";
$regex = '~^((?:[^|]*\|){2})([^|]*)\|(.*?AKS_PN)\|(.*)~';
$string = preg_replace($regex, "$1$4|$3", $string);
echo $string;
# BANG|ADAR|285816|MOTOR|GOOD||INDIA|2.4|SOFTWARE|285816_AKS|SAB_PART|AKS_PN
?>
Non-regex solution
You don't even need a regular expression here (far too complicated), just split, switch and join afterwards:
<?php
$string = "BANG|ADAR|285815|MOTOR|GOOD||INDIA|2.4|SOFTWARE|285816_AKS|SAB_PART|AKS_PN|285816";
$parts = explode("|", $string);
$parts[2] = $parts[count($parts) - 1];
$string = implode("|", $parts);
echo $string;
?>

Use Preg_match for just for string inside two certain symbols

I'm trying to use preg_match just for string inside two certain symbols for example
My Name is %^i%Ibrahem ^i.
I want to use preg_match just for ^i which is inside this two symbols %% to be font-style:italic; I've tried:
$find=array('`\^i`si');
$replace=array('font-style:italic;');
$replaced = preg_replace($find,$replace,$string);
but it replaces the last ^i too also keep in mind that the string between %% can be also %^b ^i% so I can't condition that the string have to be %^i% Help!
You could use this pattern instead:
$find = array('/%(.*?)(\^i)(.*?)%/', '/%(.*?)(\^b)(.*?)%/');
$replace = array('%$1font-style:italic;$3%', '%$1font-weight:bold;$3%');
$replaced = preg_replace('/%(.*)%/', '<span style="$1">', preg_replace($find, $replace, $string));

How to extract a collection of numbers from a string?

I need to extract a project number out of a string. If the project number was fixed it would have been easy, however it can be either P.XXXXX, P XXXXX or PXXXXX.
Is there a simple function like preg_match that I could use? If so, what would my regular expression be?
There is indeed - if this is part of a larger string e.g. "The project (P.12345) is nearly done", you can use:
preg_match('/P[. ]?(\d{5})/',$str,$match);
$pnumber = $match[1];
Otherwise, if the string will always just be the P.12345 string, you can use:
preg_match('/\d{5}$/',$str,$match);
$pnumber = $match[0];
Though you may prefer the more explicit match of the top example.
Try this:
if (preg_match('#P[. ]?(\d{5})#', $project_number, $matches) {
$project_version = $matches[1];
}
Debuggex Demo
You said that project number is 4 of 5 digit length, so:
preg_match('/P[. ]?(\d{4,5})/', $tring, $m);
$project_number = $m[1];
Assuming you want to extract the XXXXX from the string and XXXXX are all integers, you can use the following.
preg_replace("/[^0-9]/", "", $string);
You can use the ^ or caret character inside square brackets to negate the expression. So in this instance it will replace anything that isn't a number with nothing.
I would use this kind of regex : /.*P[ .]?(\d+).*/
Here is a few test lines :
$string = 'This is the P123 project, with another useless number 456.';
$project = preg_replace('/.*P[ .]?(\d+).*/', '$1', $string);
var_dump($project);
$string = 'This is the P.123 project, with another useless number 456.';
$project = preg_replace('/.*P[ .]?(\d+).*/', '$1', $string);
var_dump($project);
$string = 'This is the P 123 project, with another useless number 456.';
$project = preg_replace('/.*P[ .]?(\d+).*/', '$1', $string);
var_dump($project);
use explode() function to split those

Regex replacement with multiple occurances and different values within a string in PHP

I have this code:
<object height="510" width="650">height="510"width="650">
or this code:
<objectheight="345"width="123'> height='456'width=789>
The quotes around the values could be double, single or none. And the words could be put together or there could be one or more whitespaces. And what is important the digits as a value could be anything
So, I need to replace the integervalue in height="510" (or height='123' or height=456) with my own variable $height_val.
My code so far:
$height_val = "640";
$pattern = ??? // this regex I need to find out
$replacement = $height_val;
$string = '<objectheight="345"width="123\'> height=\'456\'width=789>'
$result = preg_replace($pattern, $replacement, $string);
And the final result should be <objectheight="640"width="123\'> height=\'640\'width=789>
The reg-ex I'd use is: height=(["']*)[0-9]*(["']*). This ensures you only get the height value with any non-alpha digit after the equals followed by an any length number.
$height_val = "640";
//$pattern = '/height=\D[0-9]*\D/' // pre comments regex
$pattern = height='/(["']*)[0-9]*(["']*)/'; //new regex
$replacement = $height_val;
$string = '<objectheight="345"width="123\'> height=\'456\'width=789>'
$result = preg_replace($pattern, $replacement, $string);
I've tested it on the following variables:
<object height="510" width="650">height="510"width="650">
<objectheight="510" width="650">height="510"width="650">
<object height='510' width="650">height="510"width="650">
<objectheight='510'width="650">height="510"width="650">
value="width=650&height=515&plugins=http://
Going forward I would recommend you try using a RegEx tester to try your own combinations. You can also use this regex reference to give you help with character classes.
Updated:
If you wish to allow for no quotation marks too use the following:

how to remove last occurance of underscore in string

I have a string that contains many underscores followed by words ex: "Field_4_txtbox" I need to find the last underscore in the string and remove everything following it(including the "_"), so it would return to me "Field_4" but I need this to work for different length ending strings. So I can't just trim a fixed length.
I know I can do an If statement that checks for certain endings like
if(strstr($key,'chkbox')) {
$string= rtrim($key, '_chkbox');
}
but I would like to do this in one go with a regex pattern, how can I accomplish this?
The matching regex would be:
/_[^_]*$/
Just replace that with '':
preg_replace( '/_[^_]*$/', '', your_string );
There is no need to use an extremly costly regex, a simple strrpos() would do the job:
$string=substr($key,0,strrpos($key,"_"));
strrpos — Find the position of the last occurrence of a substring in a string
You can also just use explode():
$string = 'Field_4_txtbox';
$temp = explode('_', strrev($string), 2);
$string = strrev($temp[1]);
echo $string;
As of PHP 5.4+
$string = 'Field_4_txtbox';
$string = strrev(explode('_', strrev($string), 2)[1]);
echo $string;

Categories