How to add slash after every string in PHP? - php

How i can add a slash or ; after every string. Here i have an Example:
This is what i have
"SKU" "TITLE" "LINK" "LINK2" "PRICE" "World of Warcraft"
But i will have like that
"SKU";"TITLE";"LINK";"LINK2";"PRICE";"World of Warcraft"
How i can made this? I work with affiliate and this Partner dont give CSV. Its only an TXT file.
So, how i can add slash into every "string"?
i already tried to add ; after every 2nd ". But it dont work with my code...
also tried with str_replace()
str_replace(" ", ";", $item);

The solution using preg_replace function:
$str = '"61926182767182" "DAS GEILE GAME" "HTTP://google.com/123129182691239" "HTTP://google.com/123129182691239" "32.59"';
$str = preg_replace("/(\"[^\"]+\")\s/", "$1;", $str);
print_r($str); // '"61926182767182";"DAS GEILE GAME";"HTTP://google.com/123129182691239";"HTTP://google.com/123129182691239";"32.59"'
(this approach can be easily extended if there would be tabs instead of spaces in the input string OR if there may be multiple spaces between words. It's more flexible)

You can split string by " " delimiter using explode() and join result array with ";" string using implode()
$str = implode('";"', explode('" "', $str))
See result in demo

Related

PHP str_replace scraped content with wild card?

I'm looking for a solution to strip some HTML from a scraped HTML page. The page has some repetitive data I would like to delete so I tried with preg_replace() to delete the variable data.
Data I want to strip:
Producent:<td class="datatable__body__item" data-title="Producent">Example
Groep:<td class="datatable__body__item" data-title="Produkt groep">Example1
Type:<td class="datatable__body__item" data-title="Produkt type">Example2
....
...
Must be like this afterwards:
Producent:Example
Groep:Example1
Type:Example2
So a big piece is the same except the word within the data-title piece. How could I delete this piece of data?
I tried a few things like this one:
$pattern = '/<td class=\"datatable__body__item\"(.*?)>/';
$tech_specs = str_replace($pattern,"", $tech_specs);
But that didn't work. Is there any solution to this?
Just use a wildcard:
$newstr = preg_replace('/<td class="datatable__body__item" data-title=".*?">/', '', $str);
.*? means match anything but don't be greedy
Assuming that the string looked like this:
$string = 'Producent:<td class="datatable__body__item" data-title="Producent">Example';
You could get the beginning and the end of the string with this:
preg_match('/^(\w+:).*\>(\w+)/', $string, $matches);
echo implode([$matches[1], $matches[2]]);
Which, in this case, will throw Producent:Example. So, then you could add this output to another variable/array you intend to use.
OR, since you mentioned replacing:
$string = preg_replace('/^(\w+:).*\>(\w+)/', '$1$2', $string);
But then again, checking as it would probably come in a variable number of lines:
$string = 'Producent:<td class="datatable__body__item" data-title="Producent">Example
Groep:<td class="datatable__body__item" data-title="Produkt groep">Example1
Type:<td class="datatable__body__item" data-title="Produkt type">Example2';
$stringRows = explode(PHP_EOL, $string);
$pattern = '/^(\w+:).*\>(\w+)/';
$replacement = '$1$2';
foreach ($stringRows as &$stringRow) {
$stringRow = preg_replace($pattern, $replacement, $stringRow);
}
$string = implode(PHP_EOL, $stringRows);
Which will then output the string like you expect.
Explaining my regex:
the first group catches the first word until the two dots :, then another group to catch the last word. I had previously specified anchors for both ends, but when breaking each line this wouldn't work as expected, so I kept only the beginning.
^(\w+:) => the word in the beginning of the string until two dots appear
.*\> => everything else until smaller symbol appears (escaped by slash)
(\w+) => the word after the smaller than symbol
Well maybe my question wasn't that good written. I had a table which I needed to scrape from a website. I needed the info in the table, but had to cleanup some parts as mentioned. The solution I finally made was this one and it works. It still has a little work to do with manual replacements but that is because of the stupid " they use for inch. ;-)
Solution:
\\ find the table in the sourcecode
foreach($techdata->find('table') as $table){
\\ filter out the rows
foreach($table->find('tr') as $row){
\\ take the innertext using simplehtmldom
$tech_specs = $row->innertext;
\\ strip some 'garbage'
$tech_specs = str_replace(" \t\t\t\t\t\t\t\t\t\t\t<td class=\"datatable__body__item\">","", $tech_specs);
\\ find the first word of the string so I can use it
$spec1 = explode('</td>', $tech_specs)[0];
\\ use the found string to strip down the rest of the table
$tech_specs = str_replace("<td class=\"datatable__body__item\" data-title=\"" . $spec1 . "\">",":", $tech_specs);
\\ manual correction because of the " used
$tech_specs = str_replace("<td class=\"datatable__body__item\" data-title=\"tbv Montage benodigde 19\">",":", $tech_specs);
\\ manual correction because of the " used
$tech_specs = str_replace("<td class=\"datatable__body__item\" data-title=\"19\">",":", $tech_specs);
\\ strip some 'garbage'
$tech_specs = str_replace("\t\t\t\t\t\t\t\t\t\t","\n", $tech_specs);
$tech_specs = str_replace("</td>","", $tech_specs);
$tech_specs = str_replace(" ","", $tech_specs);
\\ put the clean row in an array ready for usage
$specs[] = $tech_specs;
}
}

What is the correct way to str_replace until the end of string in PHP?

If I have a string like this:
myPDF12345431234
what would be the proper PHP function call to str_replace so that everything after " " rel=.... " is replaced with nothing/blank?
For further clarity, The value in between the link tags is dynamic and unknown, so I can't call it.
I'm looking for something like:
$oldstring = array('<a href="', '" rel="" *until the end_of_string* ');
$replacewith = array=('', '');
$newstring = str_replace($oldstring, $replacewith, $URL);
What is the proper way to get everything after the URL (quotation mark til the end of the string) to be replaced with nothing?
This is handled by regular expressions. The following replaces everything from rel="" to the end of the string.
$newstring = preg_replace('/ rel="".*$/','',$oldstring);
The .* means "everything" and $ means "end of string". I added a space before rel because I assume you want to drop that as well.
Use preg_match:
preg_match("/(\<a href\=\\".*\\")\srel/", "myPDF12345431234", $output_array);
Var_dump($output_array);
http://www.phpliveregex.com/p/fqQ
It sounds like what you're actually looking for is the substring of your current string up until the end of your rel attribute.
$newstring = substr($oldstring, 0, strpos($oldstring, 'rel=""'));

php preg_replace pattern - replace text between commas

I have a string of words in an array, and I am using preg_replace to make each word into a link. Currently my code works, and each word is transformed into a link.
Here is my code:
$keywords = "shoes,hats,blue curtains,red curtains,tables,kitchen tables";
$template = '%1$s';
$newkeys = preg_replace("/(?!(?:[^<]+>|[^>]+<\/a>))\b([a-z]+)\b/is", sprintf($template, "\\1"), $keywords);
Now, the only problem is that when I want 2 or 3 words to be a single link. For example, I have a keyword "blue curtains". The script would create a link for the word "blue" and "curtains" separately. I have the keywords separated by commas, and I would like the preg_replace to only replace the text between the commas.
I've tried playing around with the pattern, but I just can't figure out what the pattern would be.
Just to clarify, currently the output looks as follows:
shoes,hats,blue curtains,red curtains,tables,kitchen tables
While I want to achieve the following output:
shoes,hats,blue curtains,red curtains,tables,kitchen tables
A little bit change in preg_replace code and your job will done :-
$keywords = "shoes,hats,blue curtains,red curtains,tables,kitchen tables";
$template = '%1$s';
$newkeys = preg_replace("/(?!(?:[^<]+>|[^>]+<\/a>))\b([a-z ' ']+)\b/is", sprintf($template, "\\1"), $keywords);
OR
$newkeys = preg_replace("/(?!(?:[^<]+>|[^>]+<\/a>))\b([a-z' ']+)\b/is", sprintf($template, "\\1"), $keywords);
echo $newkeys;
Output:- http://prntscr.com/77tkyb
Note:- I just added an white-space in your preg_replace. And you can easily get where it is. I hope i am clear.
Matching white-space along with words is missing there in preg_replace and i added that only.

php cleanup phone variable

Im wanting to record on a database, peoples phone numbers. Since people enter numbers differently(based on area codes) etc, i want to normalize whatever they input into a standard manner before it goes up to a database, then when i read it back from the database and put on the page, that it comes out like this 1-954-999-9999 in this format to which i can then append the 1-954-999-9999 and can be clicked from the web app / or normal site to make a call.
All this said, i have a question.
On POST this is how im handling it
$compBizNumber = mysqli_real_escape_string($c2d, $_POST['compBizNumber']) ;
$compBizNumber = str_replace("(", "-", $compBizNumber);
$compBizNumber = str_replace(")", "-", $compBizNumber);
$compBizNumber = str_replace(" ", "-", $compBizNumber);
$compBizNumber = filter_var($compBizNumber,FILTER_SANITIZE_NUMBER_INT) ;
Is there a way to replace multiple characters in one go??
how can i go about this?
Thanks in advanced.
str_replace accepts an array as the first (and second parameter) so this will do:
$compBizNumber = str_replace(array("(", ")", " "), "-", $compBizNumber);
However, a more flexible way would be to use a regular expression to replace all non-numeric characters:
$compBizNumber = preg_replace("/[^0-9]/", "-", $compBizNumber);
This way you don't have to add all possible characters a user would enter into str_replace.
Why not use a regex to remove all except numbers:
$myNumber = "+31 (0) 43 - 123 345 67";
preg_replace("/[^0-9]/","", $myNumber);
http://codepad.org/30vUqWWC
However, beware of the + I guess you'd have to replace that with 00 instead of nothing in order to make the number work? Not 100% sure about that one.

Replace a character only in one special part of a string

When I've a string:
$string = 'word1="abc.3" word2="xyz.3"';
How can I replace the point with a comma after xyz in xyz.3 and keep him after abc in abc.3?
You've provided an example but not a description of when the content should be modified and when it should be kept the same. The solution might be simply:
str_replace("xyz.", "xyz", $input);
But if you explicitly want a more explicit match, say requiring a digit after the ful stop, then:
preg_replace("/xyz\.([0-9])+/", 'xyz\${1}', $input);
(not tested)
something like (sorry i did this with javascript and didn't see the PHP tag).
var stringWithPoint = 'word1="abc.3" word2="xyz.3"';
var nopoint = stringWithPoint.replace('xyz.3', 'xyz3');
in php
$str = 'word1="abc.3" word2="xyz.3"';
echo str_replace('xyz.3', 'xyz3', $str);
You can use PHP's string functions to remove the point (.).
str_replace(".", "", $word2);
It depends what are the criteria for replace or not.
You could split string into parts (use explode or preg_split), then replace dot in some parts (eg. str_replace), next join them together (implode).
how about:
$string = 'word1="abc.3" word2="xyz.3"';
echo preg_replace('/\.([^.]+)$/', ',$1', $string);
output:
word1="abc.3" word2="xyz,3"

Categories