Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slice a string in PHP?

Tags:

string

php

slice

Ok, so I've got this string:

"MICROSOFT CORP CIK#: 0000789019 (see all company filings)"

And I would like to cut off everything after the "CORP" bit. How would I go about doing this in PHP? I am used to Python so I am not sure how this is done.

To be clear, this is the output I want:

"MICROSOFT CORP"

I am trying:

$companyname = substr($companyname, 0, strpos($companyname, " CIK"));

and I am getting nothing showing.

Here is my full code:

<?php
include 'simple_html_dom.php';
$html = file_get_html('http://www.sec.gov/cgi-bin/browse-edgar?company=&match=&CIK=MSFT&filenum=&State=&Country=&SIC=&owner=exclude&Find=Find+Companies&action=getcompany');
$companyname = $html->find('span[class=companyName]', 0);
$companyname = substr($companyname, 0, strpos($companyname, " CIK#")+5);
$bizadd = $html->find('div[class="mailer"]');
echo $companyname;
echo "<br />";
foreach ($bizadd as $value) {
    $addvals = $value->find('span[class="mailerAddress"]');
    echo "<br />";
    foreach ($addvals as $value) {
        echo $value;
        echo "<br />";
    }
}
?>
like image 594
Steven Matthews Avatar asked Oct 08 '11 14:10

Steven Matthews


People also ask

How can I remove part of a string in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string. rtrim() - Removes whitespace or other predefined characters from the right side of a string.

What is substr () in PHP?

substr in PHP is a built-in function used to extract a part of the given string. The function returns the substring specified by the start and length parameter. It is supported by PHP 4 and above. Let us see how we can use substr() to cut a portion of the string.

How can I split a string into two strings in PHP?

explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.


2 Answers

You can either use explode() (http://php.net/explode) or a mix of substr() (http://php.net/substr) with strpos() (http://php.net/strpos).

<?php
$string = "MICROSOFT CORP CIK#: 0000789019 (see all company filings)";
$newString = substr($string, 0, strpos($string, " CIK#"));
echo $newString;

Edit: edited a few times to fit your question editing...

like image 190
Dvir Avatar answered Oct 26 '22 23:10

Dvir


You 'd find the position of "CORP" with strpos (be sure to read the giant red warning) and then cut off the relevant part with substr.

like image 42
Jon Avatar answered Oct 27 '22 00:10

Jon