The error you're seeing:
syntax error, unexpected token "public"
means that you're trying to define a method (public function extractSkuFromTitle(...)) outside of a class definition — which is not allowed in plain PHP.
✅ Explanation
In PHP, public function syntax is only valid inside a class. If you're putting this function in a standalone file or outside of a class, you'll get a syntax error.
✅ Solution
Make sure the method is defined inside a class, like this:
<?php
class ProductHelper
{
/**
* Extracts the SKU from a product title by matching the content inside the first parentheses.
*
* @param string $title The product title to extract the SKU from.
* @return string|null The extracted SKU or null if not found.
*/
public function extractSkuFromTitle($title)
{
// Match the content inside the first parentheses
if (preg_match('/\((.*?)\)/', $title, $matches)) {
return trim($matches[1]); // Return the matched SKU
}
return null; // Return null if no match found
}
}
✅ Usage Example
$helper = new ProductHelper();
$title = "Sample Product (SKU12345)";
$sku = $helper->extractSkuFromTitle($title);
var_dump($sku); // string(7) "SKU12345"
❗ Common Mistakes That Cause This Error
- Copy-pasting a method into a script without wrapping it in a class.
- Trying to define functions in a procedural PHP file using OOP syntax.
- Missing opening
{ or closing } brackets in the class, making PHP think the method is outside.
✅ If You Don't Want to Use a Class
If you're not working in an object-oriented context and just want a standalone function, use this instead:
<?php
/**
* Extracts the SKU from a product title by matching the content inside the first parentheses.
*
* @param string $title The product title to extract the SKU from.
* @return string|null The extracted SKU or null if not found.
*/
function extractSkuFromTitle($title)
{
if (!is_string($title)) {
return null;
}
if (preg_match('/\((.*?)\)/', $title, $matches)) {
return trim($matches[1]);
}
return null;
}
And call it like:
$sku = extractSkuFromTitle("Some Product (XYZ789)");
var_dump($sku); // string(6) "XYZ789"
Let me know if you're using a framework like Laravel or WordPress, and I can tailor the example accordingly!